Thanks for the reply! Apparently it was also due to the fact Mosh forgot to add this to the FINISH file in advanced API concepts:
def get_queryset(self):
queryset = Product.objects.all()
collection_id = self.request.query_params.get(‘collection_id’)
if collection_id is not None:
queryset = queryset.filter(collection_id=collection_id)
return queryset
and some additional code.
But you are also right, my database was not complete. I was able to access other product id details.
Now I have the opposite problem. I am able to delete products when It should be throwing me:
return Response({‘error’: ‘Product cannot be deleted because it is associated with an order item.’}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
my views.py:
class ProductViewSet(ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
filterset_class = ProductFilter
pagination_class = DefaultPagination
search_fields = [‘title’, ‘description’]
ordering_fields = [‘unit_price’, ‘last_update’]
def get_queryset(self):
queryset = Product.objects.all()
collection_id = self.request.query_params.get('collection_id')
if collection_id is not None:
queryset = queryset.filter(collection_id=collection_id)
return queryset
def get_serializer_context(self):
return {'request': self.request}
def destroy(self, request, *args, **kwargs):
if OrderItem.objects.filter(product_id=kwargs['pk']).count() > 0:
return Response({'error': 'Product cannot be deleted because it is associated with an order item.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
return super().destroy(request, *args, **kwargs)
class CollectionViewSet(ModelViewSet):
queryset = Collection.objects.annotate(
products_count=Count(‘products’)).all()
serializer_class = CollectionSerializer
def destroy(self, request, *args, **kwargs):
if Collection.objects.filter(id=kwargs['pk']).count() > 0:
return Response({'error': 'Collection cannot be deleted because it includes one or more products.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
return super().destroy(request, *args, **kwargs)
class ReviewViewSet(ModelViewSet):
serializer_class = ReviewSerializer
def get_queryset(self):
return Review.objects.filter(product_id=self.kwargs['product_pk'])
def get_serializer_context(self):
return {'product_id': self.kwargs['product_pk']}