Django orm group by json key in json field

I use the json field in my django model:

class JsonTable(models.Model): data = JSONField() type = models.IntegerField() 

I tried the following query, which works for normal sql fields:

 JsonTable.objects.filter(type=1).values('type').annotate(Avg('data__superkey')) 

But this causes the following error:

 FieldError: Cannot resolve keyword 'superkey' into field. Join on 'data' not permitted. 

Is there a way to make a group by json key using Django ORM or some python library without using raw sql?

Versions: Django 1.9b, PostgreSQL 9.4

UPDATE

Example 2:

 JsonTable.objects.filter(type=1).values('data__happykey').annotate(Avg('data_superkey')) 

causes the same error on happykey

+7
json python django postgresql
source share
1 answer

If you use this package https://github.com/bradjasper/django-jsonfield , there is nothing in the code for managing similar simulated related queries (data__some_json_key) Since Json data is text, you need to go to raw sql or better: use the method queryset extra() , but parsing Json in sql seems difficult.

0
source share

All Articles