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

Posted by Jonathan on Stack Overflow See other posts from Stack Overflow or by Jonathan
Published on 2010-06-05T21:32:26Z Indexed on 2010/06/05 21:52 UTC
Read the original article Hit count: 404

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):
        self.calculateField1()
        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.

Is this the correct behavior on django's side? If yes, then how can I use the new values within calculateField1?

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

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models