具有以下模型:
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'))
不起作用,请参见。在 Django 查询中使用 .extra(select={...}) 引入的值上使用 .aggregate()?和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"