Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'] 
like image 385
ezdookie Avatar asked Apr 03 '16 19:04

ezdookie


1 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'}]) 
like image 129
Airith Avatar answered Sep 17 '22 01:09

Airith