在使用ModelSerializer创建之前编辑字段

时间:2019-02-25 19:00:24

标签: django serialization django-rest-framework python-3.7

我有一个内部装有物品的托盘。我需要根据外键值为货盘分配一个特定的编号(但这还没有在代码中)。

使用邮递员,当我使用json正文进行发布时;

  1. 如果我输入一些数字字段,则会出现一个错误,指出数字不能重复。
  2. 如果我不发送号码(因为我在自定义的创建方法中给出了号码),则会收到错误消息,指出号码是必填字段。
  3. 如果我从PalletSerializer中删除数字,它会保存,但是当我需要获取它时,就没有数字了。

哪种方法是在创建之前添加数据的正确方法?这是序列化器:

class ContentSerializer(serializers.ModelSerializer):    

    class Meta:
        model = models.Content
        fields = ('id', 'quantity', 'kilograms', 'container')

class PalletSerializer(serializers.ModelSerializer):
    contents = ContentSerializer(many=True)

    class Meta:
        model = models.Pallet
        fields = ('id', 'number', 'receipt_waybill', 'client', 'contents',)

    def create(self, validated_data):
        contents_data = validated_data.pop('contents')
        number = 123456
        pallet = models.Pallet.objects.create(number=number, **validated_data)
        for content_data in contents_data:
            specifications_data = content_data.pop('specifications')
            instance = models.Content.objects.create(pallet=pallet, **content_data)
            instance.specifications.set(specifications_data)

        return pallet

1 个答案:

答案 0 :(得分:1)

您可以将number字段设置为只读。您可以通过在number = serializers.IntegerField(read_only=True)中使用PalletSerializer手动定义字段,或在序列化器的read_only_fields = ('number',)中定义class Meta来实现。

相关问题