Opened 5 years ago

Closed 5 years ago

#13705 closed (worksforme)

Calling a method from within a django model save() override

Reported by: jonathan_livni Owned by: nobody
Component: Uncategorized Version: 1.2
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


I'm overriding a django model save() method. Within the override I'm calling another method of the same class and instance which calculates one of the instance's fields based on other fields of the same instance.

class MyClass(models.Model):
    field1 = models.FloatField()
    field2 = models.FloatField()
    field3 = models.FloatField()

    def calculateField1(self)
        self.field1 = self.field2 + self.field3

    def save(self, *args, **kwargs):
        super(MyClass, self).save(*args, **kwargs)

The override method is called when I change the model in admin. Alas I've discovered that within calculateField1() field2 and field3 have the values of the instance from before I edited them in admin. If I enter the instance again in admin and save again, only then field1 receives the correct value as field2 and field3 are already updated.

This seems like wrong behavior on django's side to me.

I cannot implement the calculation within the save() as calculateField1() is actually quite long and I need it to be called from elsewhere as well.

Change History (1)

comment:1 Changed 5 years ago by kmtracey

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to worksforme
  • Status changed from new to closed

I cannot recreate this. If I cut and paste your model code into a test project/app, add a missing colon at the end of def calculateField1(self), and do a simple all works fine.

When I add a new object with values 1.0, 2.0, and 3.0 for field1, field2, and field3 respectively, then press "save and continue editing", the re-displayed value for field1 is 5.0. If I then edit the object and change the values for field2 and field3 both to 4.0, again hit save and continue editing, the value for field1 becomes 8.0.

I see the same behavior if I use the "Save" button instead, and then re-edit the object. On the first save, the value for field1 is correctly set to the sum of the other two fields. It is not necessary to save the model twice to get the calculated value set properly.

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