Django使用group by获得多个coloumn

时间:2016-02-25 11:54:33

标签: python django orm

TagNews.objects.filter(status=1).values("news","tag").annotate(total=Count('tag'))

SELECT `tags_news`.`news_id`,
       `tags_news`.`tag_id`,
        COUNT(`tags_news`.`tag_id`) AS `total`
  FROM `tags_news`
 WHERE `tags_news`.`status` = 1
 GROUP BY `tags_news`.`news_id`,
          `tags_news`.`tag_id`
 ORDER BY NULL

但我想要多个列字段和单个组,如下面的查询: -

SELECT `tags_news`.`news_id`,
       `tags_news`.`tag_id`,
        COUNT(`tags_news`.`tag_id`) AS `total`
  FROM `tags_news`
 WHERE `tags_news`.`status` = 1
 GROUP BY `tags_news`.`tag_id`
 ORDER BY NULL

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望将TagNews与tag分组,那么请获取tagnews列。这应该可行;

tag_news = TagNews.objects.filter(status=1).values("tag").annotate(total=Count('tag'))
tag_news.values("news","tag")