Issue
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(
recipient_number=e.mobile,
content=batch.content,
sender=e.contact_owner,
billee=batch.user,
sender_name=batch.sender_name
)
Does that mean doing the following (below) will loop and create all the entries first then hit the database? Is this right?
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
),
})
Solution
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)
Answered By - falsetru
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.