I am fetching some user stats daily and recording them in a model as follows (irrelevant parts are stripped off for simplicity):
class User(models.Model):
group = models.CharField(
choices=(('A', 'Group A'), ('B', 'Group B'),
))
class Stats(models.Model):
day = models.DateField()
user = models.ForeignKey(User)
follower_count = models.PositiveIntegerField()
As seen above, each user belongs to a group.
How can I get the sum each user's follower_count
s for each group over a date range?
In other words, what is the best way to build a data structure as follows using these models? Is it possible to do it with a single aggregate query?
[{
'date': '2015-07-15',
'Group A': 26, # sum of followers of users in Group A on 2015-07-15
'Group B': 15,
}, {
'date': '2015-07-16',
'Group A': 30,
'Group B': 18,
}, {
'date': '2015-07-17',
'Group A': 32,
'Group B': 25,
}]
Thank you.