Search code examples
pythondjangodjango-modelsdjango-ormdjango-jsonfield

Is there a django-orm lookup for querying nested jsonfield key?


My table has a JsonField column named meta_data. One of its entries is:

{'abc':'zyz', 'name':{'pranav':'age', 'john':'age'}}

To query on Jsonfield i use __has_key lookup:

table.objects.filter(id__in=id_list, meta_data__has_key='name')

I want to findout if there is some django lookup that helps me check if there is the key 'pranav' inside 'name' like:

table.objects.filter(id__in=id_list, meta_data__has_key__has_key='pranav')

or something like that

Thanks for any input on this...!


Solution

  • Yes you can use any list of keys you want separated by __ to traverse your JSON even if the keys do not exist. PostgreSQL will just skip the row if any of the keys don't exist down the line.