Reject or exclude filter in Django REST Framework

I have been using the Django REST Framework for a long time, but I came across a situation where I need to get everything except the well-known relationship in the API view. After reviewing the documentation again, I see no built-in mechanism to achieve this. I understand that I can override get_queryset()in my ListView and parse the parameters of a custom URL request and then do the filtering, but I'm curious if anyone has a more elegant solution?

Update

After a bit more research, this is most likely related to the django-filter question, and I cannot find any mention of any exclusive functionality. I found this:

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

which ensures the exclusion of values ​​from the results.

+4
source share
3 answers

It looks like you are looking for a custom filter

+2
source

Use the parameter excludein the filter definition inside your filter.

class MyFilterSet(FilterSet):
    negated_field__not = django_filters.NumberFilter(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

It is equivalent Model.objects.all().exclude(negated_field__exact=value). Then, from your interface, you can rule out a request for a the URL: /api/my_viewset/?negated_field__not=value.

+3
source

django-rest-framework-filters. key!= Value.

,/api/search? name!= Alex

0

Source: https://habr.com/ru/post/1537436/


All Articles