Django Rest Framework中可写的多对多字段试图保存新的子对象?

时间:2017-07-04 13:53:12

标签: django-rest-framework

编辑:这是使用django rest framework 2.3

我的模型结构有3个关系“级别”,其中一个是多对多。

class Shipment(models.Model):
    stuff...

class ShipmentItem(models.Model):
    shipment = models.ForeignKey(Shipment)
    assets = models.ManyToMany(ShipmentAsset)

class ShipmentAsset(models.Model)
    serial_number = models.CharField(unique=True)

使用Django休息框架我希望能够使用包含ShipmentItem ShipmentShipmentAsset s的有效负载发布到“Shipment”端点ShipmentItem理想情况下是一次请求。

序列化器如下..

class ShipmentAssetSerializer(serializers.ModelSerializer):
    class Meta:
         model = ShipmentAsset
         field = ('id', 'serial_number', )


class ShipmentItemSerializer(serializers.ModelSerializer):
    assets = ShipmentAssetSerializer(
        many=True, required=False, allow_add_remove=True,
    )

    class Meta:
        model = ShipmentItem
        fields = ('id', 'assets', )


class ShipmentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Shipment
        fields = (
            'id',
        )

当我发布资产部分已禁用时,cargoItem / Shipment关系似乎有效,但当我尝试在有效负载中发布资产时,它似乎正在尝试使用发布的数据创建新资产(我得到了一个关于序列号的唯一约束的错误)而不是创建新的多对多表对象。知道我做错了吗?

编辑:重要说明,我正在使用Django Rest Framework 2.3.13

0 个答案:

没有答案