1👍
✅
Perhaps a better solution (for Django >= 1.11) is to use something like this:
from django.contrib.postgres.fields.jsonb import KeyTextTransform
Car.objects.filter(options__interior__color='red').annotate(
interior_material=KeyTextTransform('material', KeyTextTransform('interior', 'options'))
).values('interior_material')
Note that you can nest KeyTextTransform
expressions to pull out the value(s) you need.
3👍
I can suggest a bit cleaner way with using:
-
django’s
Func
https://docs.djangoproject.com/en/2.0/ref/models/expressions/#func-expressions -
and postgres function
jsonb_extract_path_text
https://www.postgresql.org/docs/9.5/static/functions-json.html
from django.db.models import F, Func, CharField, Value Car.objects.all().annotate(options__interior__material = Func( F('options'), Value('interior'), Value('material'), function='jsonb_extract_path_text' ), )
- [Django]-Django/Python app logging does not working
- [Django]-Django find_each (like RoR)
- [Django]-Django MEDIA_URL returns http instead of https
- [Django]-Preserving ModelAdmin attributes (list_display, etc.) when inheriting from a custom model
0👍
Car.objects.extra(select={'interior_material': "options#>'{interior, material}'"})
.filter(options__interior__color='red')
.values('interior_material')
You can utilize .extra()
and add postgres jsonb operators
Postgres jsonb operators: https://www.postgresql.org/docs/9.5/static/functions-json.html#FUNCTIONS-JSON-OP-TABLE
👤Mani
- [Django]-Check if item is in ManyToMany field?
- [Django]-Can I have 2 Django sites using 2 different version of Python on 1 domain?
- [Django]-How can I set up django not to use in-memory database during unittest?
- [Django]-Django return user model id with L
Source:stackexchange.com