Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django bulk create objects from QuerySet

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.

like image 943
Darkstarone Avatar asked Dec 29 '17 02:12

Darkstarone


1 Answers

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

like image 104
ubadub Avatar answered Oct 04 '22 16:10

ubadub