Question

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.

Was it helpful?

Solution 2

It sounds like you are searching for custom filter backend

OTHER TIPS

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.

You can use django-rest-framework-filters. This package supports exclusion syntax in query string key!=value.

For example, /api/search?name!=Alex

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top