Django JSONField filtering

Question:

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']
Asked By: ezdookie

||

Answers:

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'}])
Answered By: Airith
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.