作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
具有以下模型:
from django_hstore import hstore
from django.db import models
class Item(VoteModel):
data = hstore.DictionaryField(db_index=True)
objects = hstore.HStoreManager()
类似于:
Item.objects.extra(select={"key": "content_item.data -> 'key'"}).aggregate(Count('key'))
不工作,比照。 Using .aggregate() on a value introduced using .extra(select={...}) in a Django Query? 和 https://code.djangoproject.com/ticket/11671 。
有效的原始 SQL 如下:
SELECT content_item.data -> 'key' AS key, count(*) FROM content_item GROUP BY key;
key | count
-----------+-------
value1 | 223
value2 | 28
value3 | 31
(3 rows)
如何通过 Django 的 ORM 获得相同的结果?
仅供引用:
Item.objects.extra(select={"key": "content_item.data -> 'key'"})
转换为:
SELECT (content_item.data -> 'key') AS "key", "content_item"."id", "content_item"."data" FROM "content_item"
最佳答案
您尝试过使用 values 和 order_by 吗?
Item.objects.extra(
select=dict(key = "content_item.data -> 'key'")
).values('key').order_by('key').annotate(total=Count('key'))
类似的东西在 PostgreSQL 和 Django 1.4 中对我有用。
关于python - Django ORM 和 hstore : counting unique values of a key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12522966/
我是一名优秀的程序员,十分优秀!