zoukankan      html  css  js  c++  java
  • 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`

    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

  • 相关阅读:
    PAT Basic 1077 互评成绩计算 (20 分)
    PAT Basic 1055 集体照 (25 分)
    PAT Basic 1059 C语言竞赛 (20 分)
    PAT Basic 1072 开学寄语 (20 分)
    PAT Basic 1049 数列的片段和 (20 分)
    蓝桥杯BASIC-13 数列排序
    蓝桥杯入门——3.序列求和
    蓝桥杯入门——2.圆的面积
    蓝桥杯入门——1.Fibonacci数列
    树的总结(遍历,BST,AVL原型,堆,练习题)
  • 原文地址:https://www.cnblogs.com/yun1108/p/9228248.html
Copyright © 2011-2022 走看看