有两种明显的方法可以解决这个问题:
首先您可以使用dotted.notation
来强制来源论证 http://django-rest-framework.org/api-guide/fields.html#core-arguments of the user
领域是user.username
而不是默认的user
.
class ProfileSerializer(serializers.ModelSerializer):
user = serializers.Field(source='user.username')
class Meta:
model = Profile
fields = ('id', 'name', 'active', 'type', 'user')
注意Field
是标准只读字段,因此您无法使用此序列化程序更新用户。
或者,如果您希望用户成为可写字段,您可以使用蛞蝓相关领域 http://django-rest-framework.org/api-guide/relations.html#slugrelatedfield像这样...
class ProfileSerializer(serializers.ModelSerializer):
user = serializers.SlugRelatedField(slug_field='username')
class Meta:
model = Profile
fields = ('id', 'name', 'active', 'type', 'user')
如果您愿意,也可以使用第二种方法,但使用只读字段,方法是添加read_only=True
to the SlugField
.