我试图获取一个特定类别的项目,然后在react应用程序中通过这个类别进行映射。我使用Django restframework创建了一个API,该框架返回此类类别的项,但使用的是post请求。以下是代码:
class ProductCategoryView(APIView):
serializer_class = ProductSerializer
permission_classes = (permissions.AllowAny, )
def post(self, request, format=None):
data = self.request.data
category = data['category']
queryset = Product.objects.order_by('-dateCreated').filter(category__iexact=category)
serializer = ProductSerializer(queryset, many=True)
return Response(serializer.data)
例如,假设我在数据库中有3类项目(教科书、期刊和小说)。在react前端应用程序中,我只想检索教科书,通过一系列教科书进行映射,并显示每本教科书,而不显示来自其他类别的任何项目。但是,由于我使用post请求,所以在实现它时遇到了困难。通过将特定类别传递给请求主体,我将返回该类别中的项。是否可以使用、get、request、并从数据库中筛选项目,这样我就只能获得教科书类别下的项目了?
发布于 2022-06-22 17:08:06
是的,您也可以使用get实现。对于搜索和过滤,我通常使用通用的ListAPIView,它也具有良好的分页功能。
from rest_framework import generics
class ProductCategoryView(generics.ListAPIView):
serializer_class = ProductSerializer
permission_classes = (permissions.AllowAny, )
queryset = Product.objects.all()
def get_queryset(self):
category = self.request.GET.get('category')
# other_filter = self.request.GET.get('other_filter')
qs = super().get_queryset()
if category:
qs = qs.filter(category__iexact=category)
# if other_filter:
# qs = qs.filter(other_field=other_field)
return qs
你的url会像这样
/产品-清单/?类别=教科书
/product-list/?category=textbooks&other_filter=other
如果您仍然想继续使用上面的代码,可以更改如下所示
def get(self, request, format=None):
category = request.GET.get('category')
qs = Product.objects.all()
if category:
qs = qs.filter(category__iexact=category)
serializer = self.serializer_class(qs, many=True)
return Response(serializer.data)
https://stackoverflow.com/questions/72718844
复制相似问题