Django rest: Dynamically include or exclude Serializer class fields

Viewed 301

I want filds of serializer dynamical include or exclude.In application after each lesson there will be a quiz but there are moments there are no quiz of the lesson, for this I need to create dynamic fields for Serializers. I try by docs DRF. But my code doesnt work

quiz/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

course/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)

error

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'.
1 Answers

You may need to add a default value for the quiz field

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