GROUP_CONCAT equivalent in Django(GROUP_CONCAT 在 Django 中的等价物)
问题描述
假设我有一张名为 fruits 的表格:
Say I have the following table called fruits:
id | type | name
-----------------
0 | apple | fuji
1 | apple | mac
2 | orange | navel
我的目标是最终得出不同types的数量和一个以逗号分隔的名称列表:
My goal is to ultimately come up with a count of the different types and a comma-delimited list of the names:
apple, 2, "fuji,mac"
orange, 1, "navel"
这可以通过 MySQL 中的 GROUP_CONCAT 轻松完成,但我在使用 Django 等效项时遇到了麻烦.这是我到目前为止所拥有的,但我缺少 GROUP_CONCAT 的东西:
This can be easily done with GROUP_CONCAT in MySQL but I'm having trouble with the Django equivalent. This is what I have so far but I am missing the GROUP_CONCAT stuff:
query_set = Fruits.objects.values('type').annotate(count=Count('type')).order_by('-count')
如果可能,我想避免使用原始 SQL 查询.
I would like to avoid using raw SQL queries if possible.
任何帮助将不胜感激!
谢谢!=)
推荐答案
Django ORM 不支持这个;如果您不想使用原始 SQL,那么您需要 分组并加入.
The Django ORM does not support this; if you don't want to use raw SQL then you'll need to group and join.
这篇关于GROUP_CONCAT 在 Django 中的等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:GROUP_CONCAT 在 Django 中的等价物
基础教程推荐
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
