Django FilterSet for JSON fields

1.1k views Asked by At

For example, I have a simple django-model:

class SimpleModel(models.Model):
    some_attr = models.JSONField() #there is [attr1, attr2, ...] in JSON

Simple view:

class SimpleView(ListCreateApivView):
    filter_backends = [DjangoFilterBackend, ]
    filterset_class = SimpleFilter

And simple filter:

class SimpleFilter(django_filters.FilterSet):
    class Meta:
        model = SimpleModel
        fields = {'some_attr': ['icontains', ]}

I wanna check is the http://127.0.0.1/simple?some_attr__icontains=['Something, that I have in db'] In my db there is JSONField, which contains [a1, a2, a3 ...], so, how can I check is value from url is in db JSONField?

3

There are 3 answers

0
Artem Minchenkov On BEST ANSWER

Thanks for answer, I solve the problem with creating custom-filter for my JSON-field, something like that:


class CharInFilter(filters.BaseInFilter, filters.CharFilter):
    pass

class MainInfoFilter(filters.FilterSet):

    some_attr = CharInFilter(method='some_attr_filter')

    def some_attr_filter(self, queryset, name, value):
        query = Q()
        for type in value:
            query |= Q(license_types__icontains=type)
        if query:
            queryset = queryset.filter(query)
        return queryset
0
Daniel On

I would override the get_queryset method like so:

views.py

import json

class SimpleView(...):

    ...

    def get_queryset(self):

        # unpack the filter:
        filter_string = self.request.GET.get('filter', {})
        filter_dictionary = json.loads(filter_string)

        # filter queryset:
        queryset = self.queryset.filter(**filter_dictionary)

        return queryset

Then you can do something like this from the frontend:

scripts.js

// create a django like filter:
var filter = JSON.stringify({
  some_attr__some_key__icontains : 'some_value' 
});

// add the filter as a parameter to the url:
var url = 'api/simple_model/?filter=' + filter;

// send the request:
$.ajax({
  url : url,
  ...
});
0
Pankaj Sajekar On

Try This it will help you. in my case, I used the JSON field for the job_location Column in Django model.py file. when I try to apply django_filter that time I face this error i resolve like that.

this code enters in the view file.

from django_filters import rest_framework as filters

class ProductFilter(filters.FilterSet):
    job_location = filters.CharFilter(field_name="job_location", lookup_expr='icontains') 

class Meta:
    model = JobPostModel
    fields = {
        'job_location': ['exact',],
    }

django_filter used in this class

from django_filters.rest_framework import DjangoFilterBackend

class JobsView(generics.ListAPIView):
     queryset = JobPostModel.objects.all()
     serializer_class = JobPostSerializer
     filter_backends = (DjangoFilterBackend)
     filterset_class = ProductFilter

and search in the browser in the URL

http://127.0.0.1:8000/jobs/?job_location=mumbai