简体   繁体   中英

Problem with passing kwargs in django rest

I have created a simple endpoint about user detail with default_lookup = pk and, if pk == 9_999_999_999 I wish to return user that is already logged in. I assume that my problem is with kwargs, am i doing something wrong?

class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
serializer_class = UserSerializer
queryset = User.objects.all()

def get(self,*args,**kwargs):
    pk = kwargs.get('pk')
    print(kwargs)
    print(f"pk {pk}")
    if pk == 9999999999:
        kwargs['pk'] = self.request.user.id
    print(kwargs)
    return self.retrieve(self,*args,**kwargs)

and output:

{'pk': 9999999999} 
pk 9999999999
{'pk': 13}
Not Found: /api/users/9999999999

You can do something like this to make easier.

class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
serializer_class = UserSerializer
queryset = User.objects.all()

def get_queryset(self):
    pk = kwargs.get('pk')
    print(kwargs)
    print(f"pk {pk}")
    if pk == 9999999999:
        kwargs['pk'] = self.request.user.id
    print(kwargs)
    return self.retrieve(self,*args,**kwargs)

and your URLs should look like this

path('name/<int:pk>/', views.UserDetailView.as_view()),

hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM