13👍
✅
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))
Recipient.objects.bulk_create(recipients)
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.
0👍
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.
- Django; is it possible to have a default value for queryset
- Invalid block tag: expected 'elif', 'else' or 'endif'
- How do you put a file in a fixture in Django?
- What is the difference between `assertIn` and `assertContains` in Django?
Source:stackexchange.com