Django JSONField过滤 [英] Django JSONField filtering
问题描述
我正在使用PostgreSQL和Django 1.9的JSONField这个新字段。所以我得到以下数据:
I'm using PostgreSQL and this new field from Django 1.9, JSONField. So I got the following data:
id|data
1 |[{'animal': 'cat', 'name': 'tom'}, {'animal': 'dog', 'name': 'jerry'}, {'animal': 'dog', 'name': 'garfield'}]
我试图弄清楚如何在此json列表中进行过滤。我尝试过这样的事情: object.filter(data__contains = {'animal':'cat'}
,但我知道这不是办法。我也一直在思考get此值并在我的代码中对其进行过滤:
I'm trying to figure out how to filter in this list of json. I tried something like: object.filter(data__contains={'animal': 'cat'}
but I know this is not the way. Also I've been thinking in get this value and filter it in my code:
[x for x in data if x['animal'] == 'cat']
推荐答案
根据django JSONField文档,它说明了数据
结构与python原始格式匹配,查询时使用的方法略有不同。
As per the django JSONField docs, it explains that that the data
structure matches python native format, with a slightly different approach when querying.
如果您知道JSON的结构,还可以过滤键为如果它们是相关字段:
If you know the structure of the JSON, you can also filter on keys as if they were related fields:
object.filter(data__animal='cat')
object.filter(data__name='tom')
通过数组访问:
object.filter(data__0__animal='cat')
您的包含示例几乎是正确的,但是您的数据在列表中,并且需要:
Your contains example is almost correct, but your data is in a list and requires:
object.filter(data__contains=[{'animal': 'cat'}])
这篇关于Django JSONField过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!