Django报错 The serializer field might be named incorrectly and not match any Got AttributeError when a
Posted yun1108
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django报错 The serializer field might be named incorrectly and not match any Got AttributeError when a相关的知识,希望对你有一定的参考价值。
1、问题描述,在设置,model部分字段的serialier时,出现如下报错
字段如下:
1 # 知识库List 2 class KnownledgeBaseListSerializer(serializers.ModelSerializer): 3 article_state = serializers.CharField(source=‘get_article_state_display‘) 4 know_classify = serializers.CharField(source=‘know_classify.name‘) 5 knowledge_source = serializers.CharField(source=‘knowledge_source.name‘,write_only=True) 6 author_for = serializers.CharField(source=‘author_for.name‘) 7 class Meta: 8 model = KnowledgeBase 9 fields = [‘theme_for‘,‘article_state‘,‘know_classify‘,‘knowledge_source‘,‘author_for‘,‘create_time‘,‘average_score‘]
2、问题原因:
1. 当场景是前端post数据过来,调用到了serializer实例的save()方法的时候,会将字段保存入库,但是数据库里面没有这个字段,所以以错误形式返回。解决如下:
1 def validate(self, attrs): 2 """ 3 attrs : 每个字段validate之后,返回的总的字段的dict 4 """ 5 del attrs["code"] 6 return attr
例中code就是model外的自定义字段,从序列化验证完成后返回的attrs中删除自定义”code”,就不会再保存这个字段
- 当场景为前端post数据过来进行实例创建的,比方说注册一个账户或者添加一个收藏,这个过程,将会调用到createmodelmixin的create方法:
1 class CreateModelMixin(object): 2 """ 3 Create a model instance. 4 """ 5 def create(self, request, *args, **kwargs): 6 serializer = self.get_serializer(data=request.data) 7 serializer.is_valid(raise_exception=True) 8 self.perform_create(serializer) 9 headers = self.get_success_headers(serializer.data) 10 return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
create最后在返回response体的时候,传递的参数serializer.data,其实做的是一个序列化的工作,它会依据你在class Meta里面设置的fields,去做序列化,将里面所有字段进行序列化,这个时候就会报错
3、解决方法如下:
1 code = serializers.CharField(max_length=6,min_length=6,required=True, 2 write_only=True,)
4、字段的write_only属性.
Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.
官方文档的说明是:设置这个属性为true,去确保create/update的时候这个字段被用到,序列化的时候,不被用到
参考:https://blog.csdn.net/Newbietan/article/details/80657202
以上是关于Django报错 The serializer field might be named incorrectly and not match any Got AttributeError when a的主要内容,如果未能解决你的问题,请参考以下文章
Flink The new key serializer must be compatible with the previous key serializer
django运行报错TypeError: object supporting the buffer API required
报错 raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)
django 运行报错view must be a callable or a list/tuple in the case of include()
记一次django的诡异报错 Could not parse the remainder: '=' from '='
Django:创建用户模型报错: (admin.E108) The value of 'list_display[4]'解决方案