可以使用相同的嵌套序列化程序输出不同的数据 - Django Rest Framework

时间:2013-07-04 11:52:30

标签: django-rest-framework

如果我有这样的话:

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')

1 个答案:

答案 0 :(得分: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'}