在保存结果后,我试图将结果从求和函数传递到另一个对象。但是,每次我更改保存对象的值时,总和聚合查询集结果都不正确。我该如何正确地做到这一点?
class Team(models.Model):
total = models.PositiveSmallIntegerField(default=0)
class Player(models.Model):
team = models.ForeignKey(Team, on_delete=models.CASCADE)
score = models.PositiveSmallIntegerField(default=0)
def save(self, *args, **kwargs)
super(Player, self).save(*args, **kwargs)
# new_total value does not get updated.
new_total = Player.objects.filter(team=self.team).aggregate(Sum('score')).get('score__sum')
Team.objects.filter(id=self.team.id).update(total=new_total)
print(new_total) # if I'm saving a new value of 15, this will still print 10
@receiver(post_save, sender=Player)
def sum(sender, instance, **kwargs):
# new_total_attempt_two value does not get updated either.
new_total_attempt_two = sender.objects.filter(squad=instance.squad).aggregate(Sum('score')).get('score__sum')
print(new_total_attempt_two) # if I'm saving a new value of 15, this will still print 10
如果我有一个得分为10的对象并将其更改为15,我希望团队模型的总数将更新为15,但仍为10。
我正在使用python 3.6,django 2.1.7。 我也尝试过使用post_save信号,但也没有成功。
答案 0 :(得分:1)
尝试一下:
oncreateView