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

查看:238
本文介绍了在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.

目前,我有一些像:
object = MyModel(name = item.name)
对象项目中的项目:

Currently, I have something like that:

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

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

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开发版本1.4中,存在 bulk_create 作为一个对象管理器方法,它将ob使用类构造函数创建的项目。查看django docs

as of the django development version 1.4, 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天全站免登陆