Django ORM & hstore: counting unique key values

Having the following model:

from django_hstore import hstore
from django.db import models

class Item(VoteModel):
    data = hstore.DictionaryField(db_index=True)
    objects = hstore.HStoreManager()

Sort of:

Item.objects.extra(select={"key": "content_item.data -> 'key'"}).aggregate(Count('key'))

not working, cf. Using .aggregate () for a value entered using .extra (select = {...}) in Django Query? and https://code.djangoproject.com/ticket/11671 .

The source SQL that works is as follows:

SELECT content_item.data -> 'key' AS key, count(*)  FROM content_item GROUP BY key;                                                                               
   key     | count 
-----------+-------
 value1    |   223
 value2    |    28
 value3    |    31
(3 rows)

How can I get the same results through Django ORM?

FYI:

Item.objects.extra(select={"key": "content_item.data -> 'key'"})

translates to:

SELECT (content_item.data -> 'key') AS "key", "content_item"."id", "content_item"."data" FROM "content_item"
+5
source share
1 answer

Have you tried the values ​​and order_by?

Item.objects.extra(
    select=dict(key = "content_item.data -> 'key'")
).values('key').order_by('key').annotate(total=Count('key'))

Something like this works for me in PostgreSQL and Django 1.4.

+7
source

All Articles