Django 1.9 JSONField order_by

oneor0 picture oneor0 · Apr 15, 2016 · Viewed 7.7k times · Source

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

Answer

Daniil Ryzhkov picture Daniil Ryzhkov · May 22, 2016

As Julien mentioned ordering on JSONField is not yet supported in Django. But it's possible via RawSQL using PostgreSQL functions for jsonb. In OP's case:

from django.db.models.expressions import RawSQL
RatebookDataEntry.objects.all().order_by(RawSQL("data->>%s", ("manufacturer_name",)))