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时,出现如下报错
字段如下:
# 知识库List
class KnownledgeBaseListSerializer(serializers.ModelSerializer):
article_state = serializers.CharField(source='get_article_state_display')
know_classify = serializers.CharField(source='know_classify.name')
knowledge_source = serializers.CharField(source='knowledge_source.name',write_only=True)
author_for = serializers.CharField(source='author_for.name')
class Meta:
model = KnowledgeBase
fields = ['theme_for','article_state','know_classify','knowledge_source','author_for','create_time','average_score']
2、问题原因:
1. 当场景是前端post数据过来,调用到了serializer实例的save()方法的时候,会将字段保存入库,但是数据库里面没有这个字段,所以以错误形式返回。解决如下:
def validate(self, attrs):
"""
attrs : 每个字段validate之后,返回的总的字段的dict
"""
del attrs["code"]
return attr
例中code就是model外的自定义字段,从序列化验证完成后返回的attrs中删除自定义”code”,就不会再保存这个字段
- 当场景为前端post数据过来进行实例创建的,比方说注册一个账户或者添加一个收藏,这个过程,将会调用到createmodelmixin的create方法:
class CreateModelMixin(object):
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
create最后在返回response体的时候,传递的参数serializer.data,其实做的是一个序列化的工作,它会依据你在class Meta里面设置的fields,去做序列化,将里面所有字段进行序列化,这个时候就会报错
3、解决方法如下:
code = serializers.CharField(max_length=6,min_length=6,required=True,
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`的更多相关文章
- AttributeError: Got AttributeError when attempting to get a value for field `password2` on serializer ` UserSerializer`...
Error_msg: AttributeError: Got AttributeError when attempting to get a value for field `password2` o ...
- Django报错:OSError: raw write() returned invalid length 4 (should have been between 0 and 2)
在使用Django时Django报错:Django报错:OSError: raw write() returned invalid length 4 (should have been between ...
- Django报错:提交表单报错---RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set.
Django报错:提交表单报错---RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and ...
- django 报错Reverse for 'detail' with keyword arguments '{'pk': '2'}' not found. 1 pattern(s) tried: ['$post/(?P<pk>[0-9]+)/$']
Django报错:Reverse for 'detail' with keyword arguments '{'pk': '2'}' not found. 1 pattern(s) tried: [' ...
- Django 报错 Reverse for 'content' not found. 'content' is not a valid view function or pattern name.
Django 报错 Reverse for 'content' not found. 'content' is not a valid view function or pattern name. 我 ...
- ubuntu pip 安装django报错解决
系统版本 ubuntu Kylin 16.04 LTS 安装pip3 安装 Django 总是提示time out,无法安装. 逛了好多论坛终于遭到了解决办法,分享保存: sudo pi ...
- 关于Django报错django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configure
报错代码:django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but se ...
- 记一次Django报错Reverse for 'indextwo' with no arguments not found. 1 pattern(s) tried: ['$index/$']
启动python manage.py runserver 打开127.0.0.1:8000,报错信息如下: Reverse for 'indextwo' with no arguments not f ...
- django报错解决:view must be a callable or a list/tuple in the case of include().
django版本:1.11.15 django应用,修改urls.py后,访问报错:TypeError at /view must be a callable or a list/tuple in t ...
随机推荐
- Python复制指定目录的各个子目录下的同名文件到指定文件夹并重命名
Python复制指定目录的各个子目录下的同名文件到指定文件夹并重命名 #编码类型 #-*- coding: UTF-8 -*- #导入包 import os import shutil srcpath ...
- 本地连接服务器的redis,jedisCluster创建问题
1.redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool 查看 ...
- [Codechef - AASHRAM] Gaithonde Leaves Aashram - 线段树,DFS序
[Codechef - AASHRAM] Gaithonde Leaves Aashram Description 给出一棵树,树的"N"节点根植于节点1,每个节点'u'与权重a[ ...
- Django教程(2)
from Django official document; Django 最初被设计用于具有快速开发需求的新闻类站点,目的是要实现简单快捷的网站开发. from 编写你的第一个 Django 应用, ...
- JVM&GC详解
1.JVM简介 JVM是java的核心和基础,在java编译器和os平台之间的虚拟处理器.它是一种利用软件方法实现的抽象的计算机基于下层的操作系统和硬件平台,可以在上面执行java的字节码程序. ja ...
- git 卡住推不上去
luoxu@lenovo:~/testGit/.git$ env | grep -i proxy 查看有没有设置代理 ALL_PROXY=socks://127.0.0.1:1080/ no_prox ...
- IntelliJ IDEA 2017.3尚硅谷-----创建的静态 Java Web
- IntelliJ IDEA 2017.3尚硅谷-----省电模式
- 开发笔记-记一个基础logback配置
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true&q ...
- wamp配置本地多站点。
' 进入C:\wamp64\wamp64\bin\apache\apache2.4.37\conf\http.conf 首先确保httpd-vhosts.conf扩展文件引入进来了,部分版本默认是不引 ...