If I have a QuerySet
created from the following command:
data = ModelA.objects.values('date').annotate(total=Sum('amount'), average=Avg('amount'))
# <QuerySet [{'date': datetime.datetime(2016, 7, 15, 0, 0, tzinfo=<UTC>), 'total': 19982.0, 'average': 333.03333333333336}, {'date': datetime.datetime(2016, 7, 15, 0, 30, tzinfo=<UTC>), 'total': 18389.0, 'average': 306.48333333333335}]>
Is it possible to use data
to create ModelB
objects from each hash inside the QuerySet
?
I realize I could iterate and unpack the QuerySet
and do it like so:
for q in data:
ModelB.objects.create(date=q['date'], total=q['total'], average=q['average'])
But is there a more elegant way? It seems redundant to iterate and create when they're almost in the bulk_create
format.
This is more efficient than your call because it uses bulk_create
, which invokes just one SQL bulk create operation, as opposed to one create per object; also, it is much more elegant:
ModelB.objects.bulk_create([ ModelB(**q) for q in data ])
As to how this works, the double asterisk unpacks a dictionary (or dictionary-like object) into keyword arguments to a Python function.
Official Django documentation: https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With