Reputation: 773
I have a table called OP, it has many columns including a column named website which is of string type. using Django-rest-framwork I want to filter out those rows which is having website=FAO,BD,CD
right now my, if I use https://...../op/?website=FAO
, returns correct data but If I can't get any data if I put many values like https://...../op/?website=FAO,CD,BD.
How can I achieve the result
here is my code and what I tried;
class op_filter(FilterSet) :
# website = filters.CharFilter('website')
website = filters.CharFilter(method='filter_by_website')
......
......
class Meta :
model = Op
fields = ['website',.........]
def filter_by_website(self , queryset , name , value):
# I get strings like FAO,CD,BD thats why I split it
website_name = set(value.strip().split(','))
return queryset.filter(website__in=website_name)
class op_ViewSet(viewsets.ModelViewSet) :
queryset = Op.objects.all().filter()
serializer_class = op_Serializer
# permission_classes = (permissions.IsAuthenticated,)
pagination_class = PageNumberPagination
filter_backends = [DjangoFilterBackend , SearchFilter , OrderingFilter]
filter_class = op_filter
how to write my filter function so that it returns the correct data.
website is a column of OP table
**
Upvotes: 0
Views: 99
Reputation: 801
Did you try to update the get_queryset
of your ViewSet ? I know you can use Filter, but it could help identify the problem. Like that :
class op_ViewSet(viewsets.ModelViewSet) :
queryset = Op.objects.all() # No need to put filter here
serializer_class = op_Serializer
# permission_classes = (permissions.IsAuthenticated,)
pagination_class = PageNumberPagination
filter_backends = [DjangoFilterBackend , SearchFilter , OrderingFilter]
def get_queryset(self):
website_parameter = self.request.query_params.get('website', None)
if website_parameter is not None:
website_name = set(website_parameter.strip().split(','))
return Op.objects.filter(website__in=website_name)
return Op.objects.all()
Upvotes: 1