如果我有这样的事情:
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')