如何仅按Django中datetime字段的月份部分聚合数据

时间:2023-01-29 16:57:51

So my model is like this:

我的模型是这样的:

class Blog(models.Model):
    title = models.CharField(max_length=100)
    publication_date = models.DateField()

And now I want to get the count of the blog posts by each month. The raw sql would look like:

现在我想按月统计博客文章的数量。原始sql应该是:

SELECT COUNT (*), EXTRACT(MONTH FROM publication_date) AS month FROM blog GROUP BY month;

One solution I found is here, it suggests that getting a date list first then loop through it using filter for each iteration. I do not like it, I am looking for a way to get the result without using loop.

我在这里找到了一个解决方案,它建议首先获取一个日期列表,然后使用过滤器对每个迭代进行循环。我不喜欢它,我正在寻找一种不用循环就能得到结果的方法。

1 个解决方案

#1


1  

You could use something to the effect of Blog.objects.filter(publication_date__range=[start_of_month, end_of_month]) to get all items from between those two dates. See range for details.

可以使用Blog.objects的效果。过滤器(publication_date__range=[start_of_month, end_of_month])从这两个日期之间获取所有项目。有关详细信息,请参阅范围。

#1


1  

You could use something to the effect of Blog.objects.filter(publication_date__range=[start_of_month, end_of_month]) to get all items from between those two dates. See range for details.

可以使用Blog.objects的效果。过滤器(publication_date__range=[start_of_month, end_of_month])从这两个日期之间获取所有项目。有关详细信息,请参阅范围。