标签:数据库 就会 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 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
标签:数据库 就会 dict erro ons char err self lse
原文地址:https://www.cnblogs.com/yun1108/p/9228248.html