postgresql Django JSONField 过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36389871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:13:14  来源:igfitidea点击:

Django JSONField filtering

pythondjangopostgresql

提问by ezdookie

I'm using PostgreSQL and this new field from Django 1.9, JSONField. So I got the following data:

我正在使用 PostgreSQL 和这个来自 Django 1.9 的新字段 JSONField。所以我得到了以下数据:

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. 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:

我想弄清楚如何在这个 json 列表中进行过滤。我尝试过类似的事情:object.filter(data__contains={'animal': 'cat'}但我知道这不是方法。我也一直在考虑获取这个值并在我的代码中过滤它:

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

回答by Airith

As per the django JSONField docs, it explains that that the datastructure 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 containsexample is almost correct, but your data is in a list and requires:

您的contains示例几乎是正确的,但您的数据在列表中并且需要:

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