[英]Django Rest Framework: Should I use URL Slugs or query parameters to list items of specific category?
Right now I have a viewset that allows me to:现在我有一个视图集,它允许我:
The problem is that in the mobile application the products will only be visible when you are inside a category and subcategory.问题在于,在移动应用程序中,只有当您位于类别和子类别中时,产品才会可见。
The product model looks something like this:产品 model 看起来像这样:
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
image = models.CharField(max_length=255)
category = models.ForeignKey(ProductCategory, related_name='products', on_delete=models.CASCADE)
subcategory = models.ForeignKey(ProductSubcategory, related_name='products', on_delete=models.CASCADE)
And the product Viewset looks like this:产品 Viewset 如下所示:
class RoutineViewSet(mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
queryset = models.Product.objects.all()
def get_serializer_class(self):
if self.action == 'list':
return serializers.ProductListSerializer
else:
return serializers.ProductDetailSerializer
Should I be using a slug or ID in the endpoint to get the items?我应该在端点中使用 slug 或 ID 来获取项目吗?
www.example.com/api/products/category/food/subcategory/snacks
www.example.com/api/products/category/2/subcategory/3
Or should I be using query parameters?或者我应该使用查询参数?
www.example.com/api/products/?category=2,subcategory=3
My instinct tells me that the easiest way would be to use query parameters and overwrite the "get_queryset" method to get different products depending on the query parameters.我的直觉告诉我,最简单的方法是使用查询参数并覆盖“get_queryset”方法,以根据查询参数获取不同的产品。 But I'm not sure if that is the standard way of doing something like this.但我不确定这是否是做这样的事情的标准方式。
Thanks谢谢
you should define Sub Category @action in your View with detail=True您应该使用 detail=True 在您的视图中定义子类别 @action
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.