I have two models as following:
我有两个模型如下:
Foo(models.Model):
total = models.IntegerField()
Bar(models.Model):
foo = models.ForeignKey(Foo)
number = models.Interger()
and what is the best solution to update total field which is the sum of numbers in Bar model when I'm saving the Foo model?
什么是更新总字段的最佳解决方案,这是我保存Foo模型时Bar模型中数字的总和?
I've tried overriding the save method on Foo model, and because Bar wasn't saved yet it didn't calculate the recent numbers(I should have saved twice)
我已经尝试覆盖Foo模型上的save方法,并且因为Bar没有保存但它没有计算最近的数字(我应该保存两次)
1 个解决方案
#1
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:
我认为你压倒保存的最初想法应该有效。如果要在Foo实例保存的情况下进行操作,则可以执行以下操作:
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:
如果您希望每次保存相关Bar实例时更新总数,那么您应该在Bar类上执行类似的覆盖:
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()
#1
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:
我认为你压倒保存的最初想法应该有效。如果要在Foo实例保存的情况下进行操作,则可以执行以下操作:
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:
如果您希望每次保存相关Bar实例时更新总数,那么您应该在Bar类上执行类似的覆盖:
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()