[Fixed]-Django annotate specific keys in json fields

28👍

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')
👤simon

3👍

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

0👍

JSONExtract is use with mysql
Syntax (‘json-field-name’, ‘json-field-key’)
~Q is used for "not equal"

from django_mysql.models.functions import JSONExtract
Listing.objects.annotate(weight=JSONExtract(‘package_dimensions’,’$.p>ackage_weight’)).filter(~Q(weight=0))

Leave a comment