Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negation or exclude filter in Django REST Framework

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.

like image 461
Fiver Avatar asked Apr 22 '14 00:04

Fiver


2 Answers

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.

like image 99
Marco Lavagnino Avatar answered Sep 28 '22 03:09

Marco Lavagnino


It sounds like you are searching for custom filter backend

like image 40
Denis Cornehl Avatar answered Sep 28 '22 04:09

Denis Cornehl