#33322 closed Bug (fixed)
Saving parent object after setting on child leads to unexpected data loss in bulk_update().
Reported by: | GwynBleidD | Owned by: | Hannes Ljungberg |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 3.2 |
Severity: | Normal | Keywords: | |
Cc: | Hannes Ljungberg, Egor R | Triage Stage: | Ready for checkin |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Consider following example:
class Child(models.Model): pass class Parent(models.Model): child = models.ForeignKey(Child, on_delete=models.CASCADE, null=True)
parent = Parent.objects.create(child=None) parent.child = Child() parent.child.save() Parent.objects.bulk_update([parent], fields=["child"])
Expected behavior:
parent model instance was updated with the ID to the child in the database.
Actual behavior:
Parent model is still referencing Null.
There should probably be some check for ForeignKeys in the bulk_update logic, and if one is updated, the ID of the child model should be re-copied to the child_id field that is actually being written to the database.
Change History (8)
comment:1 by , 3 years ago
Cc: | added |
---|---|
Summary: | bulk_update not working with foreign key when referenced model was saved after the assignment. → Saving parent object after setting on child leads to unexpected data loss in bulk_update(). |
Triage Stage: | Unreviewed → Accepted |
comment:2 by , 3 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:3 by , 3 years ago
Has patch: | set |
---|
comment:4 by , 3 years ago
Cc: | added |
---|
comment:5 by , 3 years ago
Triage Stage: | Accepted → Ready for checkin |
---|
follow-up: 8 comment:7 by , 2 years ago
The PR was merged 6 months ago but it has not landed in any release. Can someone add this to the current bugfix branch, please?
comment:8 by , 2 years ago
Replying to Manuel Baclet:
The PR was merged 6 months ago but it has not landed in any release. Can someone add this to the current bugfix branch, please?
This will be released in Django 4.1+.
Thanks for the report. This is because
child_id
is not updated afterparent.child.save()
.Related to #29497 and #32133.