如何每月查询设置职位

2024-09-26 22:44:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的模特

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}]>

你对如何接收这样的查询集有什么想法吗


Tags: submissionmodeltimemodelscountpostclassqueryset
1条回答
网友
1楼 · 发布于 2024-09-26 22:44:50

你很接近,你唯一缺少的就是一个.order_by('month_sub')(是的,我知道这听起来有点奇怪)。所以你应该写:

user.post_set.annotate(
    month_sub=ExtractMonth('submission_time')
).values('month_sub').annotate(
    count=Count('month_sub')
).order_by('month_sub')

这将导致如下查询:

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应替换为userid

您也许可以通过使用Count('id')提高微小位的性能,尽管这可能没有(明显的)影响:

user.post_set.annotate(
    month_sub=ExtractMonth('submission_time')
).values('month_sub').annotate(
    count=Count('id')
).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}]>

(做了一些格式化以便于检查结果)

相关问题 更多 >

    热门问题