Negation or exclude filter in Django REST Framework

Fiver picture Fiver · Apr 22, 2014 · Viewed 7.2k times · Source

I've used Django REST Framework for quite a while now, but have come across a situation where I need to retrieve everything but a known relation in an API view. After looking through the documentation again, I cannot see any built-in mechanism to achieve this. I realize I can override get_queryset() in my ListView and parse custom URL query parameters and then do the filtering, but I'm curious if anyone else has a more elegant solution?

Update

After a little more research, this seems to be more of a django-filter question, and I cannot find mention of any exclude functionality. I did find this:

https://bitbucket.org/mjs7231/django-rest-framework-filtering

which does provide excluding values from the results.

Answer

Marco Lavagnino picture Marco Lavagnino · Mar 22, 2017

Use the exclude parameter in filter's definition inside your filterset.

class MyFilterSet(FilterSet):
    negated_field__not = django_filters.NumberFilter(field_name='negated_field', exclude=True)

    class Meta:
        model = Model
        fields = ['some_field', 'some_other_field']

class MyViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Model.objects.all()
    serializer_class = SomeSerializer

    filter_backends = (DjangoFilterBackend,)
    filter_class = MyFilterSet

That's equivalent to Model.objects.all().exclude(negated_field__exact=value). Then, from your frontend you can exclude requesting an url like this: /api/my_viewset/?negated_field__not=value.