使用django
orm大批量插入的时候我们可以不使用for循环对一个一个的save而是使用

bulk_create来批量插入,可是使用了这个方法还需要在自己添加一个事务吗? 还是django本身对这个方法进行了事务的封装?

查看了源码(django1.5):在 django/db/models/query.py 中,看到这样的片段
with transaction.commit_on_success_unless_managed(using=self.db):
            if (connection.features.can_combine_inserts_with_and_without_auto_increment_pk
                and self.model._meta.has_auto_field):
                self._batched_insert(objs, fields, batch_size)
            else:
                objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs)
                if objs_with_pk:
                    self._batched_insert(objs_with_pk, fields, batch_size)
                if objs_without_pk:
                    fields= [f for f in fields if not isinstance(f, AutoField)]
                    self._batched_insert(objs_without_pk, fields, batch_size)

这里我们看到了一个transaction的调用 transaction.commit_on_success_unless_managed(using=self.db),那么这句话是什么意思呢?
看看他的定义: django/db/transaction.py中
def commit_on_success_unless_managed(using=None, savepoint=False):
    """
    Transitory API to preserve backwards-compatibility while refactoring.

    Once the legacy transaction management is fully deprecated, this should
    simply be replaced by atomic. Until then, it's necessary to guarantee that
    a commit occurs on exit, which atomic doesn't do when it's nested.

    Unlike atomic, savepoint defaults to False because that's closer to the
    legacy behavior.
    """
    connection = get_connection(using)
    if connection.get_autocommit() or connection.in_atomic_block:
        return atomic(using, savepoint)
    else:
        def entering(using):
            pass

        def exiting(exc_type, using):
            set_dirty(using=using)

        return _transaction_func(entering, exiting, using)

没怎么看懂这个方法的解释,从代码结构来看应该是有事务的。
那自己做个试验把,往数据库批量插入2条数据,一个正确的,一个错误的看看结果如何?

ipython做了个试验
from mngm.models import Area
a1=Area(areaname="China", code="CN", parentid='1', level='3')
a2=Area(id=1, areaname="China", code="CN", parentid='1', level='3')  #错误的记录
Area.objects.bulk_create([a1, a2])
IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")

a2=Area(areaname="Chinaa", code="CN", parentid='1', level='3')        #正确的记录
Area.objects.bulk_create([a1, a2])
[<Area: Area object>, <Area: Area object>]
所以这个操作框架已经实现了事务处理,不需要自己再添加事务就好了。

你可能正好不需要这种事务处理,看看

[Django]bulk_create 探究的更多相关文章

  1. [django]Django model中数据批量导入bulk_create()

    参考: https://www.cnblogs.com/ccorz/p/Django-model-zhong-shu-ju-pi-liang-dao-rubulkcreat.html import o ...

  2. Django model中数据批量导入bulk_create()

    在Django中需要向数据库中插入多条数据(list).使用如下方法,每次save()的时候都会访问一次数据库.导致性能问题: for i in resultlist: p = Account(nam ...

  3. django ORM 批量操作:批量插入bulk_create

    django批量create数据:bulk_create(list实例) 项目中看到这样一句 models.表名.objects.using('数据库名').bulk_create(list实例) 其 ...

  4. Django --- ajax结合sweetalert使用,分页器,bulk_create批量创建数据

    目录 ajax结合sweetalert使用 bulk_create批量插入数据 分页器的使用 ajax结合sweetalert使用 ajax可以在不刷新页面的情况下与后端进行交互,在对数据进行操作的时 ...

  5. django之ajax结合sweetalert使用,分页器和bulk_create批量插入 07

    目录 sweetalert插件 bulk_create 批量插入数据 分页器 简易版本的分页器的推导 自定义分页器的使用(组件) sweetalert插件 有这么一个需求: ​ 当用户进行一个删除数据 ...

  6. Django—ajax、前端后端编码格式,bulk_create批量插入语数据库、自定义分页

    一.ajax简介: XML也是一门标记语言该语法应用场景 1.写配置文件 2.可以写前端页面(odoo框架中 erp) 每家公司都会有属于这家公司独有的内部管理软件:专门用来开发企业内部管理软件 框架 ...

  7. django中间件CsrfViewMiddleware源码分析,探究csrf实现

    Django Documentation csrf保护基于以下: 1. 一个CSRF cookie 基于一个随机生成的值,其他网站无法得到.此cookie由CsrfViewMiddleware产生.它 ...

  8. django基础之day08,利用bulk_create 批量插入成千上万条数据

    bulk_create批量插入数据 models.py文件 class Book(models.Model): title=models.CharField(max_length=32) urls.p ...

  9. django学习总结

    tips:django官方中文文档(http://python.usyiyi.cn/django/index.html),django基础教程(http://www.ziqiangxuetang.co ...

随机推荐

  1. PHPCMS v9.5.6 通杀getshell(前台)

    漏洞url:http://wooyun.jozxing.cc/static/bugs/wooyun-2014-062881.html 很好的fuzz思路. 文章提到:文件名前面的数字是被"干 ...

  2. codevs 1054 电梯

    1054 电梯 提交地址:http://codevs.cn/problem/1054/  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 白银 Silver     题目描述 D ...

  3. GCD(ZYYS)

    [问题描述]在山的那边.海的那边有 n 个小矮人,他们生存的意义就是要保护他们的精神领袖——GCD.有一天,他们收到了一封恐吓信,说要在一个遥远的地方用维纳斯之箭射击 GCD,让他变成一根面条,n 个 ...

  4. [HNOI2002]跳蚤

    题目描述 Z城市居住着很多只跳蚤.在Z城市周六生活频道有一个娱乐节目.一只跳蚤将被请上一个高空钢丝的正中央.钢丝很长,可以看作是无限长.节目主持人会给该跳蚤发一张卡片.卡片上写有N+1个自然数.其中最 ...

  5. UVA - 11992:Fast Matrix Operations

    线段树,注意tag优先级 #include<cstdio> #include<cstdlib> #include<algorithm> #include<cs ...

  6. BZOJ4926 皮皮妖的递推

    第二次乱出题.为了方便,以m=2为例,把原式变一下形,得f(i)+f(f(i-1))=i我们先无视掉那个-1,我们发现:诶,这个东西好像斐波那契数列.具体地,我们用f(n)表示把n用斐波那契数列进行拆 ...

  7. Python中str字符串的功能介绍

    Str字符串的功能介绍 1. 字符串的操作 字符串的连接操作 符号: + 格式:str1 + str2 例如:str1 = 'I Love' str2 = 'You!' print(str1 + st ...

  8. JAVA 访问WebRoot下的目录文件

    转自 http://blog.csdn.net/jian_csdn/article/details/46119313 ClassLoader classLoader = Thread.currentT ...

  9. Flexible DEMO 实现手淘H5页面的终端适配

    <!DOCTYPE html> <html> <head> <title>淘宝flexiblejs</title> <meta cha ...

  10. Future学习

    接着上一篇继续并发包的学习,本篇说明的是Callable和Future,它俩很有意思的,一个产生结果,一个拿到结果.        Callable接口类似于Runnable,从名字就可以看出来了,但 ...