【问题标题】:Removing the primary key in class based views ( django rest framework )删除基于类的视图中的主键(django rest 框架)
【发布时间】:2025-12-21 09:15:12
【问题描述】:

问题:

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

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

但我想获取基于request.user 的配置文件,所以我在 class 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/ 处的断言错误

使用 URL 关键字参数调用的预期视图 UserProfileView 命名为“pk”。修复您的 URL 配置,或将 .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_classpermission_classdrf的其他功能,我可以轻松使用。

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

谢谢。

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    对于基于细节的视图,您需要覆盖 get_object 而不是 get_queryset

    【讨论】:

      最近更新 更多