返回当前用户使用Django的REST框架 [英] Return the current user with Django Rest Framework

查看:132
本文介绍了返回当前用户使用Django的REST框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用的深化发展的Django的API。

然而,我想创建一个具有以下端点返回当前用户视图: /用户/电流

要做到这一点,我创建了一个列表视图和过滤的queryset到发出请求的用户。该工作,但其结果是一个列表,而不是一个单一的对象。结合到分页,结果看起来太复杂,不一致的与其他端点。

我也尝试创建一个详细信息视图,过滤查询集,但DRF抱怨说我没有提供PK还是蛞蝓。

你有什么想法?


解决方案

随着你可能最好关闭爆发的一般看法和自己编写的看法是这样的。

  @api_view(['GET'])
高清CURRENT_USER(要求):
    串行= UserSerializer(request.user)
    返回响应(serializer.data)

您也可以使用像这样一类基于视图做同样的事情...

 类CurrentUserView(APIView):
    DEF得到(个体经营,要求):
        串行= UserSerializer(request.user)
        返回响应(serializer.data)

当然,这里也就是您使用串行没有要求,你同样可以直接拔掉你的用户实例所需的字段。

  @api_view(['GET'])
高清CURRENT_USER(要求):
    用户= request.user
    返回响应({
        用户名:user.username,
        电子邮件:user.email,
        ...
    })

希望有所帮助。

I am currently developping an API using Django.

However, I would like to create a view that return the current User with the following endpoint: /users/current.

To do so, I created a list view and filtered the queryset to the user that made the request. That works but the result is a list, not a single object. Combined to the pagination, the result looks way too complicated and inconsistant with the other endpoints.

I also tried to create a detail view and filtering the queryset but DRF complains that I provided no pk or slug.

Do you have any idea ?

解决方案

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,
        ...
    })

Hope that helps.

这篇关于返回当前用户使用Django的REST框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆