在 Django 中批量创建模型对象 [英] Bulk create model objects in django

查看:26
本文介绍了在 Django 中批量创建模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多对象要保存在数据库中,所以我想用它创建模型实例.

I have a lot of objects to save in database, and so I want to create Model instances with that.

使用 django,我可以创建所有模型实例,使用 MyModel(data),然后我想将它们全部保存.

With django, I can create all the models instances, with MyModel(data), and then I want to save them all.

目前,我有这样的事情:

Currently, I have something like that:

for item in items:
    object = MyModel(name=item.name)
    object.save()

我想知道是否可以直接保存对象列表,例如:

I'm wondering if I can save a list of objects directly, eg:

objects = []
for item in items:
    objects.append(MyModel(name=item.name))
objects.save_all()

如何在一笔交易中保存所有对象?

How to save all the objects in one transaction?

推荐答案

截至 django 开发,存在 bulk_create 作为对象管理器方法,它将使用类构造函数创建的对象数组作为输入.查看 Django 文档

as of the django development, there exists bulk_create as an object manager method which takes as input an array of objects created using the class constructor. check out django docs

这篇关于在 Django 中批量创建模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆