简体   繁体   English

Django JSONField 过滤

[英]Django JSONField filtering

I'm using PostgreSQL and this new field from Django 1.9, JSONField.我正在使用 PostgreSQL 和 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'}]

I'm trying to figure out how to filter in this list of json.我想弄清楚如何在这个 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:我试过类似的东西: object.filter(data__contains={'animal': 'cat'}但我知道这不是方法。我也一直在考虑获取这个值并在我的代码中过滤它:

[x for x in data if x['animal'] == 'cat']

As per the Django JSONField docs , it explains that that the data structure matches python native format, with a slightly different approach when querying.根据 Django JSONField docs ,它解释说data结构匹配 python 原生格式,查询时的方法略有不同。

If you know the structure of the JSON, you can also filter on keys as if they were related fields:如果您知道 JSON 的结构,您还可以过滤键,就好像它们是相关字段一样:

object.filter(data__animal='cat')
object.filter(data__name='tom')

By array access:通过数组访问:

object.filter(data__0__animal='cat')

Your contains example is almost correct, but your data is in a list and requires:您的contains示例几乎是正确的,但您的数据在列表中并且需要:

object.filter(data__contains=[{'animal': 'cat'}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM