python - Django rest:动态包含或排除序列化器类字段
问题描述
我想要序列化器动态包含或排除的字段。在每节课后的应用程序中都会有一个测验,但有些时候本课没有测验,为此我需要为序列化器创建动态字段。我尝试通过文档DRF。但我的代码不起作用
测验/models.py
class Quiz(TrackableDate):
name = models.CharField(max_length=100)
description = models.CharField(max_length=70)
slug = models.SlugField(blank=True, max_length=700, default=None)
is_active = models.BooleanField(default=False)
def __str__(self):
return self.name
课程/views.py
class AuthLessonDetailSerializer(AuthLessonSerializer):
quiz = serializers.CharField(source='quiz.slug')
class Meta(LessonSerializer.Meta):
fields = AuthLessonSerializer.Meta.fields + \
('description', 'link', 'quiz')
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
# Instantiate the superclass normally
super( ).__init__(*args, **kwargs)
if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
错误
Got AttributeError when attempting to get a value for field `quiz` on serializer `AuthLessonDetailSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Lesson` instance.
Original exception text was: 'NoneType' object has no attribute 'slug'.
解决方案
您可能需要default
为该quiz
字段添加一个值
quiz = serializers.CharField(source='quiz.slug', default='')
推荐阅读
- psexec - 使用 psexec 将文件从本地计算机复制到远程桌面
- android - 无法在 Android Studio Preview 3.2-beta 1 中构建我的项目
- javascript - 我无法在javascript中将颜色更改为红色
- android - 我如何设置 .equals 等于 startActivityForResult 的结果
- excel - excel函数到vba代码(独占四分位数和if函数)
- logstash - 如何将表情符号作为 Logstash 的 HTTP-OUTPUT-PLUGIN 的一部分发送到 Telegram bot
- ios - 如何在打字稿的函数中定义函数?
- asp.net-mvc - 从我在 azure 上的 mvc 应用程序获取 500 错误
- c# - C# 跳过等待方法
- python - 输入问题中的变量