I have a viewset and I override list()
method, but filtering by field stop working. How can I call filtering options from my code:
This is my viewset:
class SupplementViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
queryset = models.Product.objects.filter()
serializer_class = serializers.SuplementSerializer
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
search_fields = ('hotel', 'name')
filter_fields = ('id', 'hotel', 'name')
def perform_create(self, instance):
instance.save(product_type=models.Product.SUPPLEMENT)
def list(self, request, pk=None):
if pk == None:
supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT)
else:
supplements = models.Product.objects.get(product_type=models.Product.SUPPLEMENT, id=pk)
page = self.paginate_queryset(supplements)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(page, many=True)
result_set = serializer.data
return Response(result_set)
def get_result_set(self, supplements):
result_set = serializers.ProductSerializer(supplements, many=True).data
return result_set
Thanks for the help.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as . get() or . post() , and instead provides actions such as . list() and . create() .
APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.
The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.
def list(self, request, pk=None):
if pk == None:
supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT)
else:
supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT, id=pk)
supplements= self.filter_queryset(supplements)
page = self.paginate_queryset(supplements)
self.filter_queryset(queryset)
is what you need, but it must accept queryset.
It would be helpful to see the actual implementation of the list method:
http://www.cdrf.co/3.9/rest_framework.viewsets/ReadOnlyModelViewSet.html#list
You can directly use the self.filter_queryset
method (which is inherited from GenericAPIView
in viewsets.ModelViewSet
). In very rare scenarios you will need to override the self.filter_queryset
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With