'django related field subset average
i have two models in django app
UserDay model:
class UserDay(models.Model):
date = DateField()
@property
def avg(self):
return self.activities.aggregate(Avg('point'))
Activity model:
class Activity(models.Model):
point = models.SmallIntegerField()
userDay = models.ForeignKey(
UserDay, on_delete=models.CASCADE, related_name="activities"
)
a user day can have "n" activities. i just want to get average of last "m" activities point.
HOW CAN I DO IT?? :D
Solution 1:[1]
Since you need a average of last m activities, we can get the all activities in realtion with UserDay and sort in decreasing order for m objects.
class UserDay(models.Model):
date = DateField()
@property
def avg(self):
return self.activities.order_by('-id')[:m].aggregate(Avg('point'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | B.Anup |
