首页 > 解决方案 > Pass extra field to serializer

问题描述

I have a model for price tags, let's say it contains only price. I want to pass image of the price tag to serializer then call method for text recognition inside serializer and pass recognized price to model. But I don't need image field in my model. How do I add extra field to serializer which doesn't relate to model? This is the serializer:

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)

But I got this error:

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'.

Deleting 'image' object from validated_data doesn't help. Is there any chance to use DRF serializer field for POST request which is not in the model?

标签: djangodjango-rest-framework

解决方案


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

image = ImageField(write_only=True)

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

data = validated_data.pop('image', None)
...
return super().create(validated_data)

推荐阅读