在基于类的视图中删除主键(django rest框架)

时间:2018-01-21 12:19:23

标签: django django-rest-framework

问题:

目前在我的api / urls.py我有这一行

url(r'^profile/(?P<pk>[0-9]+)/$', views.UserProfileView.as_view()),

但我希望根据request.user获取个人资料,因此我在类UserProfileView 中的代码如下:

class UserProfileView(generics.RetrieveUpdateAPIView):
    serializer_class = UserProfileSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)
    pagination_class = LimitTenPagination

    def get_queryset(self):
        try:
            queryset = UserProfile.objects.filter(user=self.request.user)
        except:
            raise APIException('No profile linked with this user')
        return queryset

但如果我从 urls.py 文件中删除pk字段,我会收到如下错误:

  

/ api / profile /

中的AssertionError      

使用URL关键字参数调用预期视图UserProfileView   命名为#34; pk&#34;。修复您的网址,或设置.lookup_field属性   视图正确。

预期。

可能的解决方案:

我做了一个基于功能的视图,如下所示:

@api_view(['GET', 'PUT'])
def user_detail(request):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        user_profile_data = UserProfile.objects.get(user=request.user)
    except:
        raise APIException('No profile linked with this user')

    if request.method == 'GET':
        serializer = UserProfileSerializer(user_profile_data)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = UserProfileSerializer(user_profile_data, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py 文件中添加了以下行:

url(r'^me/$', views.user_detail),

这可以完成工作,但我想要一个基于类的解决方案,以便我需要使用 pagination_class permission_class drf 的其他功能,我可以轻松使用它。

截至目前,由于我只需要获取一个对象,因此分页是不可能的。

感谢。

1 个答案:

答案 0 :(得分:2)

您需要覆盖基于详细信息的视图而非get_object get_queryset。{/ p>