2

如果我有这样的事情:

class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.Field(source='owner.username')

    class Meta:
        model = Snippet
        fields = ('url', 'owner', 'title', 'code', 'linenos', 'language', 'style')

class UserSerializer(serializers.HyperlinkedModelSerializer):
    snippets = SnippetSerializer()

    class Meta:
        model = User
        fields = ('url', 'username', 'snippets')

然后它将输出 SnippetSerializer 中定义的所有字段。但我希望能够做这样的事情:

snippets = SnippetSerializer(fields=('title', 'code'))

无需像这样重复 SnippetSerializer:

class SnippetSerializerSmall(serializers.HyperlinkedModelSerializer):
    owner = serializers.Field(source='owner.username')

    class Meta:
        model = Snippet
        fields = ('title', 'code')
4

1 回答 1

4

今天刚刚在网站上发布了一些关于动态修改序列化器字段的新文档...

http://django-rest-framework.org/api-guide/serializers.html#dynamically-modifiying-fields

在这里逐字引用文档...

初始化序列化程序后,可以使用该.fields属性访问在序列化程序上设置的字段字典。访问和修改此属性允许您动态修改序列化程序。

例子

例如,如果您希望能够在初始化时设置序列化程序应该使用哪些字段,您可以像这样创建一个序列化程序类:

class DynamicFieldsModelSerializer(serializers.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)

        # Instatiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        if fields:
            # 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)

这将允许您执行以下操作:

>>> class UserSerializer(DynamicFieldsModelSerializer):
>>>     class Meta:
>>>         model = User
>>>         fields = ('id', 'username', 'email')
>>>
>>> print UserSerializer(user)
{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}
>>>
>>> print UserSerializer(user, fields=('id', 'email'))
{'id': 2, 'email': 'jon@example.com'}
于 2013-07-04T12:38:02.633 回答