pythondjangopostgresqldjango-1.9django-jsonfield

How to perform filtering with a Django JSONField?


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

Solution

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