I have the following django model that contains JSONField:
class RatebookDataEntry(models.Model):
data = JSONField(blank=True, default=[])
last_update = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'Ratebook data entries'
And data field contains this json:
{
"annual_mileage": 15000,
"description": "LEON DIESEL SPORT COUPE",
"body_style": "Coupe",
"range_name": "LEON",
"co2_gkm_max": 122,
"manufacturer_name": "SEAT"
}
Can I sort queryset by one of the data fields? This query doesn't work.
RatebookDataEntry.objects.all().order_by("data__manufacturer_name")
The documentation does not mention this possibility. It seems you cannot use order_by based on a JSONfield for the moment.
As Julien mentioned ordering on
JSONField
is not yet supported in Django. But it's possible viaRawSQL
using PostgreSQL functions for jsonb. In OP's case:Following Daniil Ryzhkov answer and Eugene Prikazchikov comment, you should be able to sort ASC and DESC on JSON data fields without annotating your queryset, by using both
RawSQL
andOrderBy
. Also, you can perform case insensitive sorting by addingLOWER
:To compare integers fields, you can cast as integer:
This is an upcoming feature which has already been added and will be released in Django 2.1, expected release of August 2018.
See https://code.djangoproject.com/ticket/24747 and https://github.com/django/django/pull/8528 for details.
Since Django 1.11,
django.contrib.postgres.fields.jsonb.KeyTextTransform
can be used instead ofRawSQL
On Django 1.10, you'll have to subclass
KeyTransform
yourself:Note: the difference between
KeyTransform
andKeyTextTransform
is thatKeyTransform
will return the JSON representation of the object, whereasKeyTextTransform
will return the value of the object.For example, if
data
is{"test": "stuff"}
,KeyTextTransform
will return'stuff'
, whereasKeyTransform
will return'"stuff"'
(which can be parsed byjson.loads
)