Search code examples
djangodjango-modelsdjango-signals

Django, update rate, signals


class Thing (model.Models):
    name = models.CharField(max_length = 222)
    ratee = models.IntegerField(default = 0)
    ...

class Rate(models.Model):
    thing = models.ForeignKey(Thing)
    user = models.ForeignKey(User)
    rate = models.IntegerField()

If user evaluate the thing(give rate in Rate), I want to automatically calculate average and save to ratee in Thing. How to make it?


Solution

  • You can do

    class Rate(models.Model):
    
        def save(self, *args, **kwargs):
            super(Rate, self).save(*args, **kwargs)
            self.thing.ratee = Rate.objects.filter(thing=self.thing).aggregate(Avg('rate'))["rate__avg"]
            self.thing.save()