python Django批量创建/更新

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Django批量创建/更新相关的知识,希望对你有一定的参考价值。

# took 72 seconds
def auto_transaction():
    for record in Record.objects.all():
        record.name = "String without number"
        record.save()


# took 17 seconds
@transaction.commit_manually
def manual_transaction():
    for record in Record.objects.all():
        record.name = "String without number"
        record.save()
    transaction.commit()


# took 0.03 seconds
def builtin():
    Record.objects.all().update(name="String without number");
# took 37 seconds
def auto_transaction():
    for i in range(10000):
        name="String number %s" %i
        Record.objects.create(name=name)


# took 2.65 seconds
@transaction.commit_manually
def manual_transaction():
    for i in range(10000):
        name="String number %s" %i
        Record.objects.create(name=name)
    transaction.commit()


# took 0.47 seconds
def builtin():
    insert_list = []
    for i in range(10000):
        name="String number %s" %i
        insert_list.append(Record(name=name))
    Record.objects.bulk_create(insert_list)

以上是关于python Django批量创建/更新的主要内容,如果未能解决你的问题,请参考以下文章

如何在不在 python 中迭代它们的情况下明显地批量更新 django 模型的所有对象?

在 Django Rest Framework 中批量更新数据

Django 批量插入数据自定义分页器多表关系的建立及Form组件(待更新。。。)

Django - 高效地批量创建继承模型

正确使用 Django 的批量更新追加到列表

如何使用 Django 进行“批量更新”?