Python 通过POST请求返回列表
我不熟悉django和python,我想返回所有具有post请求提供的外键的对象 这是我的模型:Python 通过POST请求返回列表,python,django,django-rest-framework,Python,Django,Django Rest Framework,我不熟悉django和python,我想返回所有具有post请求提供的外键的对象 这是我的模型: class Product(models.Model): name = models.CharField(max_length=200) image = models.CharField(max_length=400) price = models.CharField(max_length=200) isFavorite = models.BooleanField(d
class Product(models.Model):
name = models.CharField(max_length=200)
image = models.CharField(max_length=400)
price = models.CharField(max_length=200)
isFavorite = models.BooleanField(default=False)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
这是我的序列化程序:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name', 'image', 'price', 'isFavorite')
这是我在views.py中的代码:
class ListProductsOfCategory(generics.ListAPIView):
serializer_class = ProductSerializer()
def post(self, request, *args, **kwargs):
# catch the category id of the products.
category_id = request.data.get("category_id", "")
# check if category id not null
if not category_id:
"""
Do action here
"""
# check if category with this id exists
if not Category.objects.filter(id=category_id).exists():
"""
Do action here
"""
selected_category = Category.objects.get(id=category_id)
# get products of this provided category.
products = Product.objects.filter(category=selected_category)
serialized_products = []
# serialize to json all product fetched
for product in products:
serializer = ProductSerializer(data={
"id": product.id,
"name": product.name,
"image": product.image,
"price": product.price,
"isFavorite": product.isFavorite
})
if serializer.is_valid(raise_exception=True):
serialized_products.append(serializer.data)
else:
return
return Response(
data=serialized_products
,
status=status.HTTP_200_OK
)
此代码部分工作,返回以下响应
问题是缺少产品的主键“id”,我希望响应如下:
另外,如果有人能改进代码并使其不那么复杂,我将不胜感激
提前感谢您使用序列化程序的方式不对。您应该传入实例,它将为您提供序列化的数据;传入数据并检查是否有效用于提交数据,而不是发送数据。此外,您还可以使用
many=True
传入整个查询集:
serialized_products = ProductSerializer(products, many=True)
所以你不需要你的for循环
但实际上DRF甚至可以为您完成所有这些,因为您使用的是ListAPIView。你所需要做的就是告诉它你想要什么queryset,这是你在get\u queryset
方法中做的。因此,您所需要的是:
class ListProductsOfCategory(generics.ListAPIView):
serializer_class = ProductSerializer()
def get_queryset(self):
return Product.objects.filter(category__id=self.request.data['category_id'])
还有一个问题,我希望这是一个Post请求,如果我厌倦了作为Post请求的上述解决方案,它将返回Post方法是不允许的,非常感谢您的时间。对不起,您能帮我解决Post问题吗?为什么您需要它作为一个Post?该方法用于发送数据,而不是接收数据。我提供了一个类别idSo,为什么您不能在“获取数据”中提供该类别?