我是 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(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”,我希望响应是这样的:
1 回答

汪汪一只猫
TA贡献1898条经验 获得超8个赞
您以错误的方式使用序列化程序。你应该传入实例,它会给你序列化的数据;传入数据并检查 is_valid 是为了提交数据,而不是发送数据。此外,您可以使用以下命令传入整个查询集many=True:
serialized_products = ProductSerializer(products, many=True)
所以你不需要你的 for 循环。
但实际上 DRF 甚至会为您完成所有这些,因为您使用的是 ListAPIView。你需要做的就是告诉它你想要什么查询集,你在get_queryset方法中做什么。所以你只需要:
class ListProductsOfCategory(generics.ListAPIView):
serializer_class = ProductSerializer()
def get_queryset(self):
return Product.objects.filter(category__id=self.request.data['category_id'])
添加回答
举报
0/150
提交
取消