Conditions on django filter backend in django rest framework?

Refresh

4 weeks ago

Views

338 time

1

I am using Django filter backend on few fields which is working very good. But i want to filter fields when i get specific condition Like if user_type is basic get filter query otherwise get all objects from model. Mine code for filters is here:

http_method_names = ['get']
serializer_class = SearchSerializer
pagination_class = LargeResultsSetPagination


filter_backends = (DjangoFilterBackend,)
filter_fields = ('property_zipcode', 'property_state', 'property_county',)

The thing i need is:

def get_queryset(self):
    if self.request.query_params.get('basic',None):
       filter_backends = (DjangoFilterBackend,)
       filter_fields = ('property_zipcode', 'property_state', 'property_county',)
       return filtered_query # I want to return filter query from here.

    queryset = property.objects.all();
    return queryset

I am new to Django rest framework and django filter backend. If anyone tried do to this thing please help me out.

1 answers

3

this is what you need:

class YourClass(ModelViewSet):
    serializer_class = SearchSerializer
    pagination_class = LargeResultsSetPagination
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('property_zipcode', 'property_state', 'property_county',)

    def filter_queryset(self, queryset):
        if self.request.query_params.get('basic',None):
            queryset = super(YourClass,self).filter_queryset(self.get_queryset())
        else:
            queryset=self.get_queryset()
        return queryset

override get_queryset won't work as your expectation,because filter_queryset method is called by framework after get_queryset method,DRF get_queryset then filter it by filter_queryset method.

Ykh