16

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 ModelBobjects 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.

0

1 Answer 1

20

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think this will be more efficient, cause in the for-loop 'create' will trigger save for each element, but for bulk_create there's will be only one sql;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.