Is it possible to filter with filter_class object in methods of ViewSet class?
class ClassViewSet(mixins....., DefaultApiViewSet):
filter_class = ClassFilter
Something like:
filtered = self.filter_class.base_filters.get('something_severity').filter(queryset, "value")
CodePudding user response:
You can use queryset = self.filter_queryset(self.get_queryset())
in any method in your ViewSet. self.filter_queryset
uses the filter_class behind the scene.
CodePudding user response:
When you have setup some filters that you need in FilterSet class(MultipleChoiceFilter,...)
class CarFilter(FilterSet):
wheel = MultipleChoiceFilter(choices=Wheel.CHOICES, method='wheel_filter', widget=CSVWidget)
def wheel_filter(self, queryset, name, cars):
if cars:
...
return queryset
class Meta:
model = Car
fields = []
You have to implement filter class in the ViewSet:
class DeviceViewSet(DefaultApiViewSet):
queryset = Car.objects.all()
serializer_class = CarSerializer
filter_class = CarFilter
You may use filter of your liking in the ViewSet methods when you set it like this:
IMPORTANT! - When using widget=CSVWidget
in MultipleChoiceFilter above, it works like that:
def car_method(self, req):
queryset = self.filter_queryset(self.get_queryset())
self.filter_class({"wheel": "MEDIUM,LOW"}, queryset).qs
When we are NOT using widget=CSVWidget
it works like that:
def car_method(self, req):
queryset = self.filter_queryset(self.get_queryset())
self.filter_class({'alert_severity': ['MEDIUM', 'LOW'], 'update_state': ['is_updated']}}, queryset).qs
Finished! We filtered cars based on their wheels.