python - 通过 POST 请求返回列表

标签 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(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
        )

此代码部分起作用,它返回以下响应。

enter image description here

问题是产品的主键“id”丢失,我希望响应是这样的:

enter image description here

附注如果有人可以增强代码并使其不那么复杂,我将不胜感激。

提前致谢

最佳答案

您以错误的方式使用序列化器。您应该传入实例,它会给您序列化数据;传入数据并检查 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'])

关于python - 通过 POST 请求返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53068487/

相关文章:

python - 只能在 OSX 上的 rpy2 中导入一些包,其他包会出现 SIGSEGV 错误

python - 即使 __init__ 方法有效,python 中的 With 语句也返回 None 对象

python - 使用抽象模型定义字段关系

python - Django rest framework 如何序列化字符串列表?

python - django-filter - 将查询参数映射到字段名称

python - 从文本文件 python 中读取字符串

python - 在 Python 中使用 APSchedule 和 time.sleep() 的区别

python - A QuerySet 按聚合字段值

python - django禁用Booleanfield未在POST方法上提交

django - 如何展平 django-rest-framework 序列化程序中的对象列表?