简体   繁体   中英

Django JSONField filtering

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'}]

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']

As per the Django JSONField docs , it explains that that the data structure matches python native format, with a slightly different approach when querying.

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')

By array access:

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'}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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