SELECT on JSONField with Django

人盡茶涼 提交于 2019-12-23 02:51:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!