目前在我的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 的其他功能,我可以轻松使用它。
截至目前,由于我只需要获取一个对象,因此分页是不可能的。
感谢。
答案 0 :(得分:2)
您需要覆盖基于详细信息的视图而非get_object
get_queryset
。{/ p>