首页 > 解决方案 > 按列分组 Django orm

问题描述

我有一个users包含 4 列的数据库表,id,name,country,state我想运行一个 sql 查询,例如

SELECT country, state, name, COUNT(id) from users GROUP BY country, state, name

请问我如何使用 Django ORM 来完成这个

标签: djangodjango-rest-framework

解决方案


您可以构造一个QuerySet

from django.db.models import Count

qs = Users.objects.values('country', 'state', 'name').annotate(
    count=Count('pk')
).order_by('country', 'state', 'name')

这将构造一个查询集,它是字典的集合,其中每个字典有四个键:countrystate和。是给定,和组合的总数。namecountcountUsersnamestatecountry


推荐阅读