我有一个这样的模特
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')
(是的,我知道这听起来有点奇怪)。所以你应该写:这将导致如下查询:
(其中
123
应替换为user
的id
)您也许可以通过使用
Count('id')
提高微小位的性能,尽管这可能没有(明显的)影响:如果我在一个示例数据库上运行这个,我会得到:
(做了一些格式化以便于检查结果)
相关问题 更多 >
编程相关推荐