我有一个这样的模型
class Post(models.Model):
submission_time = models.DateTimeField()
user = models.ForeignKey(User)
我想要一个查询集,它返回用户每月发布的帖子数。
我尝试过使用 ExtractMonth :
user.post_set.annotate(month_sub=ExtractMonth('submission_time')).values('month_sub').annotate(count=Count('month_sub'))
但它给了我一个像这样的查询集:
<QuerySet [{'month_sub': 5, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}, {'month_sub': 6, 'count': 1}]>
而不是像这样的(我想要的):
<QuerySet [{'month_sub': 5, 'count': 1}, {'month_sub': 6, 'count': 7}]>
关于如何接收这样的查询集有什么想法吗?
最佳答案
你已经很接近了,你唯一缺少的是 .order_by('month_sub')
(是的,我知道这听起来有点奇怪)。所以你应该写:
user.post_set.annotate(
month_sub=ExtractMonth('submission_time')
).values('month_sub').annotate(
count=Count('month_sub')
)<b>.order_by('month_sub')</b>
这将导致查询如下所示:
SELECT EXTRACT(MONTH FROM `post`.`submission_time`) AS `month_sub`,
COUNT(EXTRACT(MONTH FROM `post`.`submission_time`)) AS `count`
FROM `post`
WHERE `post`.`user_id` = 123
GROUP BY EXTRACT(MONTH FROM `post`.`submission_time`)
ORDER BY `month_sub` ASC
(其中 123
应替换为 用户
的 id
)。
通过使用 Count('id')
,您也许可以稍微提高性能一点点,尽管这可能没有(明显的)影响:
user.post_set.annotate(
month_sub=ExtractMonth('submission_time')
).values('month_sub').annotate(
count=Count(<b>'id'</b>)
).order_by('month_sub')
如果我在示例数据库上运行它,我会得到:
<QuerySet [{'count': 273, 'month_sub': 1},
{'count': 172, 'month_sub': 2},
{'count': 565, 'month_sub': 3},
{'count': 59, 'month_sub': 4},
{'count': 452, 'month_sub': 5},
{'count': 550, 'month_sub': 6},
{'count': 622 'month_sub': 7},
{'count': 43, 'month_sub': 8},
{'count': 357, 'month_sub': 9},
{'count': 378, 'month_sub': 10},
{'count': 868, 'month_sub': 11},
{'count': 293, 'month_sub': 12}]>
(进行了一些格式化以便于检查结果)
关于python - 如何查询设置每月的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50793243/