Search code examples
pythondjangopostgresqlormhstore

Django ORM & hstore : counting unique values of a key


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()

Something like:

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

doesn't work, cf. Using .aggregate() on a value introduced using .extra(select={...}) in a Django Query? and https://code.djangoproject.com/ticket/11671.

The raw SQL which works is the following:

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 hte same results through Django's 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"

Solution

  • Have you tried with 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.