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?
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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With