[Django]-Django filter if an optional key in json exists

37πŸ‘

βœ…

You can use has_key on JSONField.
JSONField and HStoreField share this look up – docs.

X.objects.filter(data__has_key='key_1')

Here is an example based on my project, I used has_key on JSONField in FilterSet (django_filters.rest_framework), to implement filtering by key (if key doesn’t exists returns 0 results):

filters.py:

class XFilter(FilterSet):
   data_search_by_key =  django_filters.CharFilter(method='filter_data_key',
        help_text='Search by key')

   def filter_data_key(self, qs, name, value):
        qs = X.objects.filter(data__has_key=value)
        return qs
πŸ‘€montxe

6πŸ‘

You can exclude all NULL values and empty strings using:

queryset  = queryset.exclude(data__key1__isnull=True).exclude(data__key1__exact='')

1πŸ‘

Newer versions of Django ship with JSONField for multiple databases, not just PostgreSQL, which you can import like this:

from django.models import JSONField

The Django documentation contains instructions on how to query JSONField. In particular, to answer your question, you can see if a JSONField has a particular key by using __has_key, like this:

>>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})
<Dog: Meg>
>>> Dog.objects.filter(data__has_key='owner')
<QuerySet [<Dog: Meg>]>
πŸ‘€Flimm

Leave a comment