将额外的字段传递给序列化器

时间:2019-09-06 09:50:38

标签: django django-rest-framework

我有一个价格标签模型,假设它只包含价格。我想将价格标签的图像传递给序列化器,然后在序列化器中调用用于文本识别的方法,并将识别出的价格传递给模型。但是我的模型中不需要像场。如何为序列化器添加与模型无关的额外字段? 这是序列化器:

class CartProductSerializer(serializers.ModelSerializer):
    image = ImageField()

    class Meta:
        model = CartProduct
        fields = '__all__'

    def create(self, validated_data):
        data = validated_data['image']
        path = default_storage.save('tmp/somename.jpg', ContentFile(data.read()))
        detect_pricetag(path)
        return super().create(validated_data)

但是我得到了这个错误:

Got AttributeError when attempting to get a value for field `image` on serializer `CartProductSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `CartProduct` instance.
Original exception text was: 'CartProduct' object has no attribute 'image'.

validated_data删除“图像”对象无济于事。 是否有机会将DRF序列化器字段用于模型中不存在的POST请求?

1 个答案:

答案 0 :(得分:1)

您不希望在序列化CartProduct时使用该字段,因此它应该是只写的。

image = ImageField(write_only=True)

此外,您也不想将其用于实例化CartProduct,因此在保存之前,应从验证数据中将其删除:

data = validated_data.pop('image', None)
...
return super().create(validated_data)
相关问题