Override ModelViewSet's queryset with filter backends applied
<p>Is it possible to take into account <code>MyModelViewSet</code>'s <code>filter_backends</code> when creating custom queryset?</p>

<pre><code>class MyModelViewSet(viewsets.ModelViewSet):
    filter_backends = (CustomFilter, )
    serializer_class = MySerializer

    def get_queryset(self):
        # It should not return all objects, but only results from `CustomFilter`
        queryset = LedgerEntry.objects.all()
        # some extra filtering
        return queryset
</code></pre>

<p>How should I implement this?</p>

<p><strong>Django</strong>: 1.10</p>

<p><strong>Django Rest Framework</strong>: 3.4.6</p>

<p>Yes you can. Just extend <code>filter_queryset</code> method of ViewSet</p>

<pre><code>class MyModelViewSet(viewsets.ModelViewSet):
    filter_backends = (CustomFilter, )
    serializer_class = MySerializer

    def filter_queryset(self, queryset):
        # super needs to be called to filter backends to be applied
        queryset = super().filter_queryset(queryset)
        # some extra filtering
        return queryset
</code></pre>

<p>In action methods in ViewSet it actually does this</p>

<pre><code>queryset = self.filter_queryset(self.get_queryset())
</code></pre>

<p>So your queryset that is sent to serializer is the one that created by <code>get_queryset</code> and then filtered with <code>filter_queryset</code></p>

python django python-3.x django-rest-framework