2

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...!

Pranav Totala
  • 148
  • 2
  • 14
  • 2
    What about `meta_data__name__has_key='pranav'`? – Willem Van Onsem Aug 08 '19 at 14:17
  • 1
    yes, you can traverse deeply even if a key is not present, without problem. Any key works, if it's not there, the row will just be skipped. So `table.objects.filter(meta_data__hello__world__has_key='ok')` will just return an empty queryset but won't generate an error. – dirkgroten Aug 08 '19 at 14:19

1 Answers1

2

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.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42