Python 在Django Rest框架API中,如何返回用户名而不是id?
这是我的模型Python 在Django Rest框架API中,如何返回用户名而不是id?,python,python-3.x,django,rest,class,Python,Python 3.x,Django,Rest,Class,这是我的模型 class FollowerModelSerializer(ModelSerializer): user = CharField(source='slug') class Meta: model = Profile fields = ['user', 'followers'] 这是序列化程序 class FollowerModelViewSet(ModelViewSet): queryset = Profile.objec
class FollowerModelSerializer(ModelSerializer):
user = CharField(source='slug')
class Meta:
model = Profile
fields = ['user', 'followers']
这是序列化程序
class FollowerModelViewSet(ModelViewSet):
queryset = Profile.objects.all()
serializer_class = FollowerModelSerializer
allowed_methods = ('GET', 'HEAD', 'OPTIONS')
def list(self, request, *args, **kwargs):
self.queryset = self.queryset.filter(id=request.user.id)
return super(FollowerModelViewSet, self).list(request, *args, **kwargs)
这就是API
以下是回应:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"user": "pop",
"followers": [
1,
4
]
}
]
问题:它正在返回追随者的ID。我应该如何让它返回追随者的用户名?您可以使用:
class FollowerModelSerializer(ModelSerializer):
user=CharField(source='slug')
followers=SlugRelatedField(
slug_field='username',
多=真,
只读=真
)
类元:
模型=外形
字段=['user','followers']
因此,这将使用
followers
关系中包含的对象的用户名
。您能更具体地说明问题是什么吗?请看,.@AMC:我想OP希望追随者成为一个列表“追随者”:[“username1”,“username2”]
@testuser1:你能给这个问题添加预期的结果吗?@WillemVanOnsem我想OP希望追随者成为一个列表“追随者”:[“username1”,“username2”]我得到了那部分,只是不清楚问题或障碍是什么。@WillemVanOnsem是绝对正确的。这就是我现在需要的,而不是ID,我只需要用户名。我已经发布了所有与此查询对应的代码。哦,妈的,这就是我所需要的。与蛞蝓有关的领域。我确实觉得自己很愚蠢,因为我之前不知道这件事。非常感谢!
class FollowerModelSerializer(ModelSerializer):
user = CharField(source='slug')
followers = SlugRelatedField(
slug_field='username',
many=True,
read_only=True
)
class Meta:
model = Profile
fields = ['user', 'followers']