首页 > 解决方案 > 键入错误以在 django rest 框架中创建和更新我的列表

问题描述

我正在尝试使用我的 api 来创建和更新捆绑包中的产品。我这样做了:

模型.py

class Business(models.Model):
    name = models.CharField(max_length=155)

class Product(models.Model):
    business = models.ForeignKey(
        Business,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
    name = models.CharField(max_length=200)
    description = models.TextField(null=True, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Product"



class Bundle(models.Model):
    business = models.ForeignKey(
        Business,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
    name = models.CharField(max_length=100)
    description = models.TextField(null=True, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    products = models.ManyToManyField(Product, related_name="bundles",blank=True, null=True, through="BundleProduct")

    class Meta:
        verbose_name = "Bundle"


    def __str__(self):
        return self.name

class BundleProduct(models.Model):

    bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, related_name="bundleproducts")
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="bundleproducts")
    number = models.IntegerField(default=1)

    class Meta:
        verbose_name = "Bundle of Product"


    def __str__(self):
        return str(self.product.name) + " do " + self.bundle.name

    def get_absolute_url(self):
        return reverse("BundleProduct_detail", kwargs={"pk": self.pk})

这是我的serializers.py:

class ProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = "__all__"        

class BundleProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = BundleProduct
        fields = "__all__"


class BundleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Bundle
        fields = "__all__"

我的视图集.py

class ProductViewSet(viewsets.ModelViewSet):

    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    model = Product


class BundleProductViewSet(viewsets.ModelViewSet):

    queryset = BundleProduct.objects.all()
    serializer_class = BundleProductSerializer
    model = BundleProduct


class BundleViewSet(viewsets.ModelViewSet):

    queryset = Bundle.objects.all()
    serializer_class = BundleSerializer
    model = Bundle

当我尝试在 bundleproducts 中发布一些产品时,我收到“类型不正确。预期的 pk 值,收到的列表。”

阅读此错误后,我发现了一些与 PrimaryKeyRelatedField 和 SlugRelatedField 相关的问题。我知道我需要覆盖,但我不知道该怎么做。

这是一个如何发布的示例:

{
    "number": 1,
    "bundle": 2,
    "product": 
         [
            1,
            2
         ]
}

在观看了 Neil 评论的视频后,我创建了以下方法:

class BundleSerializer(
    serializers.ModelSerializer
):
    products = ProductSerializer(many=True)

    def create(self, validated_data):
        products = validated_data.pop('products')
        bundle = BundleProduct.objects.create(**validated_data)
        for product in products:
            BundleProduct.objects.create(**product, bundle=bundle)
        return Bundle


    class Meta:
        model = Bundle
        fields = "__all__"

但不起作用。我收到此错误:“TypeError at /api/v1/bundle/

'name' 是此函数的无效关键字参数"

标签: pythondjangodjango-rest-frameworkdrf-queryset

解决方案


这里的问题是您将列表发布到BundleProduct的产品字段,但它是一个ForeignKey. 要加入Bundlea Product,只需POST

{
  "bundle": 2,
  "product" 1,
  "number": 1
}

你可以重复这个:

{
  "bundle": 2,
  "product" 4,
  "number": 1
}

将另一个产品 4 添加到同一个捆绑包中,依此类推。只要确保你一个一个地做它们,而不是像你之前做的那样在一个列表中。


推荐阅读