如何在DRF中发布数组数据

时间:2019-07-18 07:37:47

标签: django django-rest-framework

当我发布到数组{"productId":[1, 2, 3]}之类的json时。

我遇到了错误 Cannot assign "[<Product: Short Sleeve>, <Product: Short Sleeve>, <Product: Short Sleeve>]": "FittingCartItem.productId" must be a "Product" instance.

我已经尝试在get_serializer函数中添加many=True参数。 我不知道如何解决这个问题...

serializers.py

class ItemListSerializer(serializers.ModelSerializer):
    product = ProductSerializer(source='productId', read_only=True)
    memberId = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), write_only=True, required=False)
    productId = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), write_only=True, many=True)
    is_live = serializers.BooleanField(default=True)

    class Meta:
        model = FittingCartItem
        fields = '__all__'

views.py

class ItemListView(generics.ListCreateAPIView):
    serializer_class = ItemListSerializer
    queryest= FittingCartItem.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            headers = self.get_success_headers(serializer.data, many=True)
            return Response(serializer.data, status=status.HTTP_201_CREATED,
                            headers=headers)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

models.py

class FittingCartItem(models.Model):
    memberId = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='fittingcarts')
    productId = models.ForeignKey(Product, on_delete=models.CASCADE)
    created_time = models.DateTimeField(auto_now_add=True)
    is_live = models.BooleanField(default=True)

1 个答案:

答案 0 :(得分:0)

在您的序列化程序中,您希望您的产品由ProductSerializer进行序列化,这将导致序列化程序在JSON输入中期望使用“ Product”实例而不是productId。

您需要的是告诉序列化程序将产品作为productId,这可以通过使用PrimaryKeyRelatedField来实现。

您需要删除:

product = ProductSerializer(source='productId', read_only=True)

这将解决您的问题,因为DRF自动将模型中的ForeignKey用作PrimaryKeyRrlatedFields。但是,如果未将productId定义为ForeignKey,而是将ManyToMany关系等定义为外键,则需要将其添加如下:

productId = PrimaryKeyRelatedField(many=True, read_only=True)