首页 > django 的Group by 相关问题,怎么实现group by之后的选择字段。

django 的Group by 相关问题,怎么实现group by之后的选择字段。

django内置有group by功能

已知一消息表有字段如下:
id, receiver ,bbs ,comment ,reply ,unread ,cat ,createTime

现在使用django的groupby功能

notifications = Notification.objects.all().order_by('-createTime')

notifications = notifications.values('bbs', 'cat').annotate(count=Count('bbs'))

取出的结果如下:
[{'count': 2, 'bbs': 5656, 'cat': 2}, {'count': 13, 'bbs': 5655, 'cat': 1}, {'count': 1, 'bbs': 5655, 'cat': 3}, {'count': 2, 'bbs': 5647, 'cat': 3}, {'count': 1, 'bbs': 5651, 'cat': 1}, {'count': 1, 'bbs': 5650, 'cat': 1}]

现在问题来了,我想让django的group by 返回整个表中所有字段
据我所知,values有这个功效,但是加上annotate之后就是groupby的字段了。而不是最后结果选择的字段了。
如果不加values,那么默认的是groupby主键id。

求助各位朋友,这个该怎么处理。


首先你想像一下你在sql里要实现你的目的会怎么做?

select bbs, count(1), max(receiver), max(comment) from 表 group by bbs

那你应该知道可以在django里类似来做

notifications.annotate(
    sum_bbs=Count('bbs'),
    max_receiver=Max(receiver),
    max_comment=Max(comment)
).values('bbs', 'sum_bbs', 'max_receiver', 'max_comment')
【热门文章】
【热门文章】