仅将 ModelSerializer 中的特定字段发送到客户端 - django rest framework

send just a specific filed on ModelSerializer to client - django rest framework

我有一个 Serializer 如下所示:

class KlassStudentSerializer(ModelSerializer):
    student = ProfileSerializer()
    klass = KlassSerializer()

class Meta:
    model = KlassStudents
    fields = ['pk', 'student', 'klass']

我只想在一个视图中发送 klass 个值,在另一个视图中只发送 student 个值。我该怎么做?

class DynamicFieldsModelSerializer(ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)
        exclude = kwargs.pop('exclude', None)

        # Instantiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__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.keys())
            for field_name in existing - allowed:
                self.fields.pop(field_name)

        if exclude is not None:
            not_allowed = set(exclude)
            for exclude_name in not_allowed:
                self.fields.pop(exclude_name)


class KlassStudentSerializer(DynamicFieldsModelSerializer):
    student = ProfileSerializer()
    klass = KlassSerializer()

    class Meta:
        model = KlassStudents
        fields = ['pk', 'student', 'klass']

像这样使用:

serializer1 = KlassStudentSerializer(data=data, fields=('klass'))
serializer2 = KlassStudentSerializer(data=data, fields=('student'))

serializer3 = KlassStudentSerializer(data=data, exclude=('id', 'klass'))
serializer4 = KlassStudentSerializer(data=data, exclude=('id', 'student'))