1π
β
I think your original idea of overriding save should work. If itβs to operate when a Foo
instance saves then something along the lines of:
def save(self, *args, **kwargs):
self.total = sum([x.number for x in self.bar_set.all()])
super(Foo, self).save(*args, **kwargs)
If you want the total to update each time a relevant Bar
instance is saved then you should instead do a similar override on the Bar
class:
def save(self, *args, **kwargs):
super(Bar, self).save(*args, **kwargs)
self.foo.total = sum([x.number for x in self.foo.bar_set.all()])
self.foo.save()
π€Garry Cairns
Source:stackexchange.com