Opened 3 years ago

Closed 3 years ago

Last modified 2 years ago

#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 Mariusz Felisiak, 3 years ago

Cc: Hannes Ljungberg 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: UnreviewedAccepted

Thanks for the report. This is because child_id is not updated after parent.child.save().

Related to #29497 and #32133.

comment:2 by Hannes Ljungberg, 3 years ago

Owner: changed from nobody to Hannes Ljungberg
Status: newassigned

comment:3 by Hannes Ljungberg, 3 years ago

Has patch: set
Version 0, edited 3 years ago by Hannes Ljungberg (next)

comment:4 by Egor R, 3 years ago

Cc: Egor R added

comment:5 by Mariusz Felisiak, 3 years ago

Triage Stage: AcceptedReady for checkin

comment:6 by Mariusz Felisiak <felisiak.mariusz@…>, 3 years ago

Resolution: fixed
Status: assignedclosed

In ed201803:

Fixed #33322 -- Fixed loss of assigned related object when saving relation with bulk_update().

comment:7 by Manuel Baclet, 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?

in reply to:  7 comment:8 by Mariusz Felisiak, 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+.

Note: See TracTickets for help on using tickets.
Back to Top