Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

python - 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']
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...