Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django annotate specific keys in json fields

I'm using Django 1.9 and Postgres 9.5. I have a model (MyModel) with a JSONField (django.contrib.postgres.fields). The JSON value has the same structure in all the objects in the model.

{
"key1": int_val_1,
"key2": int_val_2
}

I want to order my queryset by a value of a specified key in my JSONField. Something like

MyModel.objects.annotate(val=F('jsonfield__key1')).order_by('val')

This does not work - i get the following error

Cannot resolve keyword 'key1' into field. Join on 'jsonfield' not permitted.

Is there anyway i can achieve this?

like image 619
Mr T. Avatar asked Feb 08 '17 13:02

Mr T.


2 Answers

for Django >= 1.11, you can use:

from django.contrib.postgres.fields.jsonb import KeyTextTransform
MyModel.objects.annotate(val=KeyTextTransform('key1', 'jsonfield')).order_by('val')
like image 71
simon Avatar answered Nov 04 '22 16:11

simon


An updated answer for this question:

At current time of writing (Django 3.1), you can now order exactly as you had hoped without needing any helper functions:

MyModel.objects.order_by('jsonfield__key1')
like image 2
alukach Avatar answered Nov 04 '22 18:11

alukach