Reputation: 2001
I am using django-filter to filter my Queryset
on the basis of url params.
class WorklistViewSet(ModelViewSet):
serializer_class = MySerializer
queryset = MyModel.objects.all()
filter_backends = [DjangoFilterBackend, ]
filterset_fields = ['class', ]
# possible values of *class* which is allowed to be passed in the url params are ['first', 'second', 'ALL'].
class MyModel(BaseModel):
CLASS_CHOICES = (
(FIRST_CLASS, 'first'),
(SECOND_CLASS, 'second'),
)
class = models.CharField(choices=CLASS_CHOICES, max_length=3, )
URLs http://127.0.0.1:8000?class=first
and http://127.0.0.1:8000?class=first
are giving the expected results.
I want that when http://127.0.0.1:8000?class=ALL
is called, all the records in my table should be listed i.e without filtering.
How can i do this while using django-filter
?
Upvotes: 2
Views: 910
Reputation: 811
You may want to use Filter.method, as explained in the docs.
In your case, I would do as follows:
class F(django_filters.FilterSet):
klass = CharFilter(method='my_custom_filter')
class Meta:
model = MyModel
fields = ['klass']
def my_custom_filter(self, queryset, name, value):
if value == 'ALL':
return queryset
return queryset.filter(**{
name: value,
})
Be also reminded that class
is a reserved word in Python and cannot be used as a variable name. I've used klass
instead, although that's used as something else in many Python books and may be confusing.
Upvotes: 1