你好!我有一个视图模型:
class MyModels(models.Model):
name = CharhField(max_lenght=100)
address = CharField(max_lenght=100)
我有一个这样的序列化程序:
class MySerializer(ModelSerializer):
class Meta:
model = MyModel
fields = ('name', 'address', 'code')
name = CharhField(max_lenght=100)
address = CharField(max_lenght=100)
code = CharField(max_lenght=100)
也就是说,我的序列化程序包含一个附加字段。因此,事实证明“设置”:
class MyViewSet(CreateModelMixin, ListModelMixin):
http_method_names = ['post']
queryset = MyModels.objects
serializer_class = UserSerializer
保存结果时,它会因以下错误而崩溃:
AttributeError: Got AttributeError when attempting to get a value for field `code` on serializer `MySerializer`.
app_1 | The serializer field might be named incorrectly and not match any attribute or key on the `MyModel` instance.
app_1 | Original exception text was: 'MyModel' object has no attribute 'code'.
此错误发生在生成 MyViewSet 的 Respone 中。请告诉我,是否有可能以某种方式从验证数据中删除此“代码”?
您可以指定一个不在模型中的字段
write_only=True
以避免此错误。并重载create
.