AssertionError报错:Serializer声明字段未加入fields选项求助
解决AssertionError:序列化器字段未在fields中声明的问题
错误信息
AssertionError: The field 'uploaded_file' was declared on serializer LessonPlanNotesSerializer, but has not been included in the 'fields' option
需求场景
发送POST请求时提交title、details及多个文件,文件需存入子模型LessonStudyMaterial,因此在LessonPlanSerializer中添加uploaded_file字段用于数据校验,触发上述错误。
模型代码
class LessonPlan(models.Model): planner=models.ForeignKey('LessonPlanner', on_delete=models.CASCADE) title=models.CharField(max_length=100, null=True, blank=True) details=models.TextField(null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class LessonStudyMaterial(models.Model): Lesson=models.ForeignKey('LessonPlan', on_delete=models.CASCADE) file=models.FileField(upload_to=get_upload_path, null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True)
序列化器代码
class LessonPlanSerializer(serializers.ModelSerializer): uploaded_file=serializers.ListField(child=serializers.FileField(max_length=2000)) class Meta: model = LessonPlan fields=['id', 'planner', 'title', 'details', 'uploaded_file',]
问题原因及解决方法
- 类名不匹配是核心问题:错误提示里的序列化器是
LessonPlanNotesSerializer,但你提供的序列化器类名是LessonPlanSerializer。要么是你实际代码中序列化器类名写错了,要么是视图里调用了错误的序列化器类——比如视图里用了LessonPlanNotesSerializer,但这个类里声明了uploaded_file却没在fields列表中添加。 - 修正字段配置:如果确实存在
LessonPlanNotesSerializer,检查该类,确保声明uploaded_file后,在Meta的fields里加上这个字段。 - 完善多文件存储逻辑:另外,你需要在序列化器的
create方法里手动处理文件,把每个文件关联到新建的LessonPlan实例,生成对应的LessonStudyMaterial记录,示例代码如下:
class LessonPlanSerializer(serializers.ModelSerializer): uploaded_file = serializers.ListField(child=serializers.FileField(max_length=2000)) class Meta: model = LessonPlan fields = ['id', 'planner', 'title', 'details', 'uploaded_file'] def create(self, validated_data): # 取出上传的文件列表,从校验数据中移除 uploaded_files = validated_data.pop('uploaded_file', []) # 创建LessonPlan主模型实例 lesson_plan = LessonPlan.objects.create(**validated_data) # 循环创建子模型记录 for file in uploaded_files: LessonStudyMaterial.objects.create(Lesson=lesson_plan, file=file) return lesson_plan
内容的提问来源于stack exchange,提问作者Neplox Null
相关产品推荐
相关产品推荐

