0

I'm using 2 different classes to perform get and retrieve operations.

class Stock(ListAPIView):
    serializer_class=StockSerializer
    queryset=Stock.objects.all()

class StockView(RetrieveAPIView):
    serializer_class = StockSerializer
    lookup_field = 'slug'

    def get_queryset(self, slug):                    
            collection = Stock.objects.get(slug=slug)            
        return collection

    def get(self, request, slug):
        collection = self.get_queryset(slug)
        serializer = CollectionSerializer(collection)
        
        return Response(
            serializer.data, 
            status=status.HTTP_200_OK
        )

but I want to perform both operations from a single class,i.e I don't want to write 2 different classes. So how to handle both (GET & RETRIEVE ) from a single class ?. Can we do that using generic APIViews? Thankx in advance

2

1 Answer 1

1

If you only require GET and RETRIEVE operation then you can use ReadOnlyModelViewSet.

from rest_framework.viewsets import ReadOnlyModelViewSet

class StockView(ReadOnlyModelViewSet):
    serializer_class = StockSerializer
    lookup_field = 'slug'
    queryset = Stock.objects.all()
Sign up to request clarification or add additional context in comments.

2 Comments

can we user generic API for get and retrieve? Instead of using modelviewset
@YoshiHutchinson you can use GenericAPIView but then you will have to write a lot of manual code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.