如何在My Update APIView中获取lookup_field值?

时间:2018-06-04 10:31:47

标签: python django django-rest-framework

如何在My Update APIView中获取lookup_field值?

下面是我的代码:

class UserAdminDeleteAPIView(RetrieveUpdateAPIView):
    model = User
    serializer_class = UserAdminSerializer
    permission_classes = []
    lookup_field = "username"

    def get_object(self, queryset=None): 
        username = self.request.data.get('username')  # there I get None
        obj = User.objects.get(username=username)
        return obj

当我通过localhost:8000/api/users/user10/delete访问API时,我无法获取用户名(user10)。

我如何获得username参数?

1 个答案:

答案 0 :(得分:0)

您可以使用self.kwargs属性

在基于类的视图中访问url的kwargs
def get_object(self, queryset=None): 
    username = self.kwargs.get('username')
    obj = User.objects.get(username=username)
    return obj

请注意,在网址格式中,您应使用username作为参数名称:

url(r'^articles/(?P<username>\w+)/$', UserAdminDeleteAPIView.as_view()),