django - 按列分组 Django orm
问题描述
我有一个users
包含 4 列的数据库表,id,name,country,state
我想运行一个 sql 查询,例如
SELECT country, state, name, COUNT(id) from users GROUP BY country, state, name
请问我如何使用 Django ORM 来完成这个
解决方案
您可以构造一个QuerySet
:
from django.db.models import Count
qs = Users.objects.values('country', 'state', 'name').annotate(
count=Count('pk')
).order_by('country', 'state', 'name')
这将构造一个查询集,它是字典的集合,其中每个字典有四个键:country
、state
和。是给定,和组合的总数。name
count
count
Users
name
state
country
推荐阅读
- reactjs - 大量的辅助函数是否会增加发送给客户端的包大小?
- javascript - 从对象数组中查找键值
- java - Process Oracle DB->column value change, in a Spring-boot-app-container
- javascript - D3.js Brush and Zoom line chart Error:
attribute d: Expected number - g++ - /bin/ld 找不到 lstdc++ 但 libstdc++.so 确实存在
- php - HTML 和 PHP - 如何在单个页面上分隔 2 个表单?
- snmpsharpnet - 如何使用 snmpsharpnet 更改发送端口
- docker - Docker:如何将大文件夹包含到容器中?
- ios - 如果 UITapGestureRecognizer 安装在顶级 UIWindow keyWindow 上,则无法获得非零位置
- android - 如何在后台(连续)运行颤振应用程序以跟踪位置