[Fixed]-Django bulk create objects from QuerySet

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

👤ubadub

Leave a comment