使用 Django Rest Framework 返回当前用户 [英] Return the current user with Django Rest Framework
问题描述
我目前正在使用 Django 开发 API.
I am currently developing an API using Django.
但是,我想创建一个返回当前用户的视图,端点如下:/users/current/
.
However, I would like to create a view that returns the current User with the following endpoint: /users/current/
.
为此,我创建了一个列表视图并过滤了发出请求的用户的查询集.这有效,但结果是一个列表,而不是单个对象.结合分页,与其他端点相比,结果看起来过于复杂和不一致.
To do so, I created a list view and filtered the queryset on the user that made the request. That works, but the result is a list, not a single object. Combined with pagination, the result looks way too complicated and inconsistent compared to other endpoints.
我还尝试创建详细视图并过滤查询集,但 DRF 抱怨我没有提供 pk 或 slug.
I also tried to create a detail view and filtering the queryset, but DRF complains that I provided no pk or slug.
你有什么想法吗?
推荐答案
有了这样的东西,你可能最好摆脱通用视图并自己编写视图.
With something like this you're probably best off breaking out of the generic views and writing the view yourself.
@api_view(['GET'])
def current_user(request):
serializer = UserSerializer(request.user)
return Response(serializer.data)
你也可以使用基于类的视图来做同样的事情......
You could also do the same thing using a class based view like so...
class CurrentUserView(APIView):
def get(self, request):
serializer = UserSerializer(request.user)
return Response(serializer.data)
当然,也不要求您使用序列化程序,您同样可以从用户实例中提取您需要的字段.
Of course, there's also no requirement that you use a serializer, you could equally well just pull out the fields you need from the user instance.
@api_view(['GET'])
def current_user(request):
user = request.user
return Response({
'username': user.username,
'email': user.email,
...
})
希望有所帮助.
这篇关于使用 Django Rest Framework 返回当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!