问题
My application is heavily reliant on APIs that unpredictably make changes to the way they return data. For this reason, I've chosen to use PSQL and JSONFields with Django.
I've seen plenty of examples/docs on how to filter by values in a JSONField, but I haven't seen any that allow me to SELECT on these values.
What I know works;queryset.filter(jsonfield__key_name = 'value')
What I want to know how to do;queryset.values('jsonfield__key_name')
Thanks in advance!
回答1:
The answer is a RawSQL expression;
queryset.annotate(value = RawSQL("(jsonfield->%s)", ('key_name',)))
queryset.values('value')
The first argument to RawSQL
is like a template string, the second argument will fill in the first's %s
UPDATE: apparently Django 2.1+ now supports my original expected behavior;
queryset.values('jsonfield__key_name')
回答2:
Since Django 2.1, transforms are supported in order_by()
, values()
and values_list()
, so you can now use this:
queryset.values('jsonfield__key_name')
Here's the relevant ticket and pull request.
来源:https://stackoverflow.com/questions/42379475/select-on-jsonfield-with-django