Reputation: 383
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?
Upvotes: 2
Views: 2067
Reputation: 20672
You don't want to use the field when serializing a CartProduct
, so it should be write-only.
image = ImageField(write_only=True)
Also you don't want it to be used to instantiate a CartProduct
, so you should remove it from the validated data before saving:
data = validated_data.pop('image', None)
...
return super().create(validated_data)
Upvotes: 5