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='')
π€Moses Koledoye
- [Django]-Name '_' is not defined
- [Django]-Django Templates β Changing context for an 'include' template
- [Django]-Django vs PHP+framework
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
- [Django]-How do I install an old version of Django on virtualenv?
- [Django]-Django + PostgreSQL: How to reset primary key?
- [Django]-Different db for testing in Django?
Source:stackexchange.com