Home > Net >  Django FilterSet for JSON fields
Django FilterSet for JSON fields

Time:04-29

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?

CodePudding user response:

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,
  ...
});

CodePudding user response:

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
  • Related