31

我试图了解 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
    ),
})
4

3 回答 3

53

问题中的第二个代码创建了一个对象,因为它传递了一个带有 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)
于 2013-08-22T14:39:20.840 回答
2

官方示例:

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'),
 ])
于 2020-09-15T14:02:36.790 回答
0
name = request.data.get('name')
period = request.data.get('period')
email = request.data.get('email')
prefix = request.data.get('prefix')
bulk_number = int(request.data.get('bulk_number'))

bulk_list = list()
for _ in range(bulk_number):
    code = code_prefix + uuid.uuid4().hex.upper()
    bulk_list.append(
        DjangoModel(name=name, code=code, period=period, user=email))

bulk_msj = DjangoModel.objects.bulk_create(bulk_list)
于 2021-09-04T10:24:09.367 回答