To get started with class based views, you need to import the APIView class from the rest_framework.views module. And then create a class that inherits from the APIView. Then you can define methods that show what you want to do. see below
class ProductList(APIView): def get(self, request): queryset = Product.objects.select_related('collection').all() serializer = ProductSerializer(queryset, many=True, context={'request': request}) return Response(serializer.data)
def post(self, request): serializer = ProductSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)This is the same logic as the ‘product_list’ view function where we get to specify http methods on top of such functions and use if else blocks.
Now that we have a class based view, in order to use it..you have to go to your urls.py file and then reference the class view. see below
urlpatterns = [ path('products/', views.ProductList.as_view()) '''adding the as_view() method converts the classbased view into a function that works as a normal function view''']This is how the product_detail function will be converted into a class based view, with the same functionality
class ProductDetail(APIView): def get(self, request, id): product = get_object_or_404(Product, pk=id) serializer = ProductSerializer(product) return Response(serializer.data)
def put(self, request, id): product = get_object_or_404(Product, pk=id) serializer = ProductSerializer(product, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data)
def delete(self, request, id): product = get_object_or_404(Product, pk=id) if product.orderitems_set.count() > 0: return Response({'error': 'Product cannot be deleted because it is associated with an order item'}, status=HTTP_405) product.delete() return Response(status=status.HTTP_204_NO_CONTENT)Note that you need to update its urlpattern as well.