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

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

时间: 2024-08-01 04:04:52

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`的相关文章

Django报错 No module named 'django.templates'

前言 Django 模板报错了 修改方法: 将你的工程文件下(my_site)的settings.py中的TEMPLATES中的templates字段全部改为template, 亲测可用~^~ Django报错 No module named 'django.templates' 原文地址:https://www.cnblogs.com/yf-html/p/9314280.html

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. | Django报错

Django报错 | "django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.问题解决方案 1 问题分析 django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. 解读:django.core.except

python2.6 使用pip安装django报错

之前处理过这个问题,因为没有记录,所以第二次踩坑了,所以此次留存处理记录 centos6.5.默认的python2.6.pip1.5.4 安装django pip install django 执行结果: Downloading/unpacking django Downloading Django-2.1.1.tar.gz (8.6MB): 8.6MB downloaded Running setup.py (path:/tmp/pip_build_root/django/setup.py)

Django报错解决方法

无法使用Django新建项目:'django-admin.py'不是内部或外部命令找到site-packages/django/bin(如 D:\Program Files\Anaconda3\Lib\site-packages\django\bin),把这个路径加入系统环境变量中. error: unrecognized arguments: getall原因:django版本和代码里的requirements.txt要求的不符解决:重装django制定版本的代码 要用 pip 安装指定版本的

django报错must be str, not dict

Django出现报错 TypeError at /main/mmp/workticket/create/app/ must be str, not dict Request Method: GET Request URL: http://127.0.0.1:8000/main/mmp/workticket/create/app/ Django Version: 2.1 Exception Type: TypeError Exception Value: must be str, not dict

python3 Django 报错RuntimeWarning的解决办法

我们在shell下运行Django的时候遇到这样的报错: C:\python\python3\lib\site-packages\django\db\backends\sqlite3\base.py:57: RuntimeWarning: SQLite received a naive datetime (2018-09-26 17:35:53.152861) while time zone support is active. RuntimeWarning) 这个原因是我们在sitting.p

django报错:django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?

django 迁移数据库报错 django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.Did you install mysqlclient? 解决方案:在settings.py同级目录中的__init__.py文件中加入: import pymysql pymysql.install_as_MySQLdb() 原文地址:https://www.cnblogs.com/pfeiliu/p/12045021

安装Django报错的问题

cmd中在指定目录下进行 setup.py install 报错:from setuptools import setup, find_packages ImportError: No module named set 网上查解决方法写到: wget http://peak.telecommunity.com/dist/ez_setup.pypython ez_setup.py 不理解什么意思 输入wget http://peak.telecommunity.com/dist/ez_setup.

Django 报错no sucn column: OpretionalError

1.报错原因:新增的字段未能同步数据库 2.解决办法:删除整个数据库,然后重新编译,然后over 1 1.rm -rf db.sqlites3 #删除数据库 2 2.rm -rf cmdb/migrarions/ #删除app下的migrations 3 3.python manage.py makemigrations --empty cmdb 4 4.python manage.py makemigrations 5 5.python manage.py migrate 原文地址:https