Opened 12 months ago

Closed 12 months ago

Last modified 12 months ago

#34933 closed Bug (duplicate)

update_or_create() does not persist field changes in save() when performing an update

Reported by: Crispin Ali Basah Owned by: nobody
Component: Database layer (models, ORM) Version: 4.2
Severity: Normal Keywords: update_or_create
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

It seems when update_or_create() is updating an object, field updates set in the model's overriden save() method is not persisted in the database.

The following simple model illustrates this behavior. field1 is set via the default={...} argument while field2 is an increment of field1 by 1 performed in the model's overridden save() method.

class Test(models.Model):
    field1 = models.PositiveSmallIntegerField(blank=True, null=True)
    field2 = models.PositiveSmallIntegerField(blank=True, null=True)

    def save(self, *args, **kwargs):
        self.field2 = self.field1 + 1
        super().save(*args, **kwargs)

The following call for update_or_create() inserts the object with id 1

>>> (obj, is_created) = Test.objects.update_or_create(id=1, defaults={'field1': 1})
>>> Test.objects.get(id=1).field1
1
>>> Test.objects.get(id=1).field2
2

The following call updates the same object

>>> (obj, is_created) = Test.objects.update_or_create(id=1, defaults={'field1': 10})
>>> Test.objects.get(id=1).field1
10
>>> Test.objects.get(id=1).field2
2

However, field2 does not get updated to 11.

Change History (2)

comment:1 by Crispin Ali Basah, 12 months ago

Resolution: duplicate
Status: newclosed

comment:2 by Crispin Ali Basah, 12 months ago

Duplicate of ticket:34099

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