因此,我正在用Django(DRF)开发一些虚拟的Electron 商务应用程序,我对如何编写好的REST API感到有点困惑.
Models
class Category(models.Model):
name = models.Char...
class Product(models.Model):
category = models.ForeignKey(...)
name = models.Char...
Views
class ProductListView(APIView):
def get(self, request, category_slug=None):
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
serializer = ProductSerializer(products, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
First Question
因此,我的问题是,我是否应该将带有捕获值(Categori_Slug)的过滤逻辑放在这个视图中,或者如果我创建两个端点会不会更清楚?
Second Question
在DRF中,通过结果/端点发送多个数据的底层代码是不是很好的做法?
return Response({data: serializer.data, other_data: serializer_other.data}, status=st...)
因此,正如我一直在学习的那样,通过一个响应API只传递一个序列化程序.data,但如果我希望该客户端还可以访问其他一些数据,该怎么办?将其拆分到多个视图中比让客户端发出多个请求更好吗?
PS: This is my first Stackoverflow question so I would appreciate some feedback on this as well.个