首页 > 解决方案 > 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'.

标签: pythondjangodjango-rest-framework

解决方案


您可能需要default为该quiz字段添加一个值

quiz = serializers.CharField(source='quiz.slug', default='')

推荐阅读