码迷,mamicode.com
首页 > 其他好文 > 详细

Django报错 The serializer field might be named incorrectly and not match any Got AttributeError when attempting to get a value for field `author_for` on serializer `KnownledgeBaseListSerializer`

时间:2018-06-26 12:34:15      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:数据库   就会   dict   erro   ons   char   err   self   lse   

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”,就不会再保存这个字段

  1. 当场景为前端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 attempting to get a value for field `author_for` on serializer `KnownledgeBaseListSerializer`

标签:数据库   就会   dict   erro   ons   char   err   self   lse   

原文地址:https://www.cnblogs.com/yun1108/p/9228248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!