[Fixed]-How to update a sum field without using aggregation on save?

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

Leave a comment