Django 1.4 - bulk_create与列表 [英] Django 1.4 - bulk_create with a list
问题描述
如果没有循环遍历列表,我该如何做,这将会消除bulk_create的含义。
例如:
而不是...
对于列表中的x:
bulk_create ...
我如何...
以一种有效的方式对整个列表进行bulk_create
列表包含:
list = ['abc','def' 'ghi']
这只是一个id的列表,而不是直接进入的形式bulk_create(不使用输入字段格式化)。但是,我想可以在将其传递到bulk_create之前修改列表。
bulk_create在单个调用中,
将对象列表作为单个参数。在你的例子中你正在做的就是循环,并且做 create()
aList = [
条目(标题=Django 1.0发布),
条目(标题=Django 1.1宣布),
条目(标题=破碎:Django真棒 )
]
Entry.objects.bulk_create(aList)
aList
是指已经实例化并需要批量创建一个查询的对象列表。如果您没有尚未保存的实例列表,并且列出了值,则可以使用以下内容创建列表:
values = ['abc','def','ghi']
#一个未保存的条目模型实例的列表
aList = [Entry(headline = val)for val值]
或者,您可以列出映射到模型的原始字典值:
values = [{headline =abc},{headline =def},{headline =ghi}]
aList = [值中的val的值(** vals)]
I have a list, which I would like to bulk_create entries for in the database.
How can I do this without looping through the list, which I presume, would take away the point of bulk_create.
For example:
Instead of...
for x in list:
bulk_create...
How could I...
bulk_create for the entire list at once in an efficient manner
List contains:
list = ['abc', 'def', 'ghi']
It's simply a list of id's, not in the form that's ready to fed directly into bulk_create (not formatted with the entry fields). However, I suppose it would be possible to modify the list before passing it into bulk_create.
bulk_create
takes a list of objects as a single arg, in a single call. What you are doing in your example would be the same as looping and doing create()
Referencing: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create
aList = [
Entry(headline="Django 1.0 Released"),
Entry(headline="Django 1.1 Announced"),
Entry(headline="Breaking: Django is awesome")
]
Entry.objects.bulk_create(aList)
aList
refers to a list of objects that you already have instantiated and need to create in bulk with one query. If for instance you didn't already have that list of unsaved instances, and you had a list of values, you could then create your list with something like:
values = ['abc', 'def', 'ghi']
# a list of unsaved Entry model instances
aList = [Entry(headline=val) for val in values]
Or maybe you have a list of raw dictionary values that map to the model:
values = [{headline="abc"}, {headline="def"}, {headline="ghi"}]
aList = [Entry(**vals) for vals in values]
这篇关于Django 1.4 - bulk_create与列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!