[Solved]-Creating many related objects like INSERT … SELECT in SQL


You can’t do INSERT .. SELECT with django ORM, but you can do a bulk insert (since django 1.4):

m = Message.objects.create(*args)
recipients = []
for email in ModelWithEmails.active.values_list('email', flat=True):
    recipients.append(Recipient(message=m, email=email))


Or a tiny bit more efficient:

m = Message.objects.create(*args)
emails = ModelWithEmails.active.values_list('email', flat=True)
Recipient.objects.bulk_create([Recipient(message=m, email=email) for email in emails])


For INSERT .. SELECT you’ll have to fall back to raw SQL.


Django ORM doesn’t need user to use raw sql any more. It is very convenient, but it may be not very flexible.
If you want to use ORM, bulk_create will be your friend, just as Pavel Anossov said.

Leave a comment