django - 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?
解决方案
您不想在序列化 a 时使用该字段CartProduct
,因此它应该是只写的。
image = ImageField(write_only=True)
此外,您不希望它用于实例化 a CartProduct
,因此您应该在保存之前将其从验证数据中删除:
data = validated_data.pop('image', None)
...
return super().create(validated_data)
推荐阅读
- javascript - Ajax 获取对 RestApi 的请求
- javascript - Node.js 获取 mysql 数据并附加到对象
- python - 熊猫数据框中的逐行替换操作
- javascript - 使用拆分功能时出错:未捕获的类型错误:无法读取 null 的属性“1”
- python - Tkinter after() 方法只执行一次
- python - Leetcode 问题 1038. 二叉搜索树到大和树 --> Python
- git - Github Pages Publishing 主页 URL 不变
- c# - mysql while(datareader.Read()) 不执行
- python - 如何仅在空单元格_python中在df中的列之间复制
- javascript - 实现语言切换器