I have a Post model that has a datetime.date field for posted_date. I need to find how many posts are made by a user on each day. Creating a query for each day seems silly.
I couldn’t figure out how to make the aggregation API query using annotate.
Is
Post.objects.filter(author=someuser).annotate(dailycount=Count('posted_day'))
the correct way? Then, how do I use this to get number of posts for a particular day?
My model is:
class Post(models.Model):
posted_day=models.DateField(default=date.today)
author=models.ForeignKey(User,null=True)
You are almost there. You need two additional clauses:
The
values('posted_day')enables the grouping, and the emptyorder_byensures the results are ordered byposted_dayso the default ordering doesn’t interfere.The clearest documentation of this seems to be in the Django Aggregation docs section on the Order of
annotate()andvalues()clauses.valuesreturns alistofdictslike:so if you wanted the last day the user posted, it would be the last item in the list:
You can then compare
datetotoday()to see if they match, and if they don’t the user didn’t post today, and if he did, he postedcounttimes.