Django bulk_create function example

前端 未结 2 1745
半阙折子戏
半阙折子戏 2021-02-06 23:58

I\'m trying to understand bulk_create in Django

This was my original query I\'m trying to convert:

for e in q:
    msg = Message.objects.create(
                 


        
2条回答
  •  失恋的感觉
    2021-02-07 00:22

    The second code in the question create a single object, because it pass a set with a Message object.

    To create multiple objects, pass multiple Message objects to bulk_create. For example:

    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)
    

提交回复
热议问题