I am able to sort collections separately, but not all together. My error:
Looks like something is not defined, tried reuploading and migrating database as suggested by stackflow, no difference.
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']}
urls.py
router = routers.DefaultRouter()
router.register(‘products’, views.ProductViewSet, basename=‘products’)
router.register(‘collections’, views.CollectionViewSet)
products_router = routers.NestedDefaultRouter(router, ‘products’, lookup=‘product’)
products_router.register(‘reviews’, views.ReviewViewSet, basename=‘product-reviews’)
urlpatterns = router.urls + products_router.urls