I am looking for a way to update multiple objects more efficiently than calling .save()
on each of them.
I have code, which uses .filter()
to load objects. Then it communicates with an external service, in order to decide what need to be done with each object. Finally I have a list of objects with updated values, which I need to save.
This code works, but is too slow:
for o in l: o.save()
Searching for suggestions I have so far found .bulk_create()
and .update()
bulk_create
works great for new objects. But replacing above loop with model.objects.bulk_create(l)
produces IntegrityError: UNIQUE constraint failed:
, probably because it is trying to create new objects rather than updating existing objects.
Using .update()
does not appear to be applicable to my use case either, because it will update all objects in the set with the same value. In my case I have computed a different value for each of the objects, that I need to save.
Is there a faster solution than calling .save()
on each object?