Django bulk_create函数示例

时间:2013-08-22 14:35:17

标签: python django django-models

我正在尝试理解Django中的bulk_create

这是我正在尝试转换的原始查询:

for e in q:
    msg = Message.objects.create(
        recipient_number=e.mobile,
        content=batch.content,
        sender=e.contact_owner,
        billee=batch.user,
        sender_name=batch.sender_name
    )

这是否意味着执行以下操作(下面)将循环并首先创建所有条目然后命中数据库?这是对的吗?

msg = Message.objects.bulk_create({
    Message (
        recipient_number=e.mobile,
        content=batch.content,
        sender=e.contact_owner,
        billee=batch.user,
        sender_name=batch.sender_name
    ),
})

2 个答案:

答案 0 :(得分:32)

问题中的第二个代码创建了一个对象,因为它传递了一个带有Message对象的集合。

要创建多个对象,请将多个Message对象传递给bulk_create。例如:

objs = [
    Message(
        recipient_number=e.mobile,
        content=batch.content,
        sender=e.contact_owner,
        billee=batch.user,
        sender_name=batch.sender_name
    )
    for e in q
]
msg = Message.objects.bulk_create(objs)

答案 1 :(得分:0)

官方示例:

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()

现在,要批量创建

Entry.objects.bulk_create([
        Entry(headline='This is a test'),
        Entry(headline='This is only a test'),
 ])