I have two model instances, rec1 and rec2, but each has different fields updated:
rec1 = MyModel(id=1, name="John") # Only 'name' is changed
rec2 = MyModel(id=2, age=30) # Only 'age' is changed
Now, I want to update both records efficiently using bulk_update(). However, bulk_update() requires a fixed list of fields, meaning:
updated_fields = ['name', 'age']
model.objects.bulk_update([rec1, rec2], fields=updated_fields)
This updates both fields in both records, even though:
- rec1 only needs to update name
- rec2 only needs to update age
Goal: Update only the changed fields for each record in a single query. Avoid unnecessary updates to unchanged fields.
Issue: bulk_update() applies the same field list to all records, leading to redundant updates.
Question: Is there a way to update only the modified fields per record efficiently in a single query? Or is there an alternative approach to handle this in Django ORM?
model.objects.bulk_update(instances_to_update, fields=updated_fields)
where updated_fields is a list.
i was expecting updated_fields as a iteration type function.