[Python] drf url parameter lookup

Discussão em 'Python' iniciado por Stack, Fevereiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm creating an endpoint api/users/ with Django REST framework which should return some data about the user by id. It's all good, but I want to obtain a lookup parameter for my User model from the url's parameters. There are lookup_field and lookup_url_kwarg attributes of GenericAPIView, but they seem to be useless here, because they work with parameters specified in URLConf, if I understand it right. So, my question is how to get object from the db when I go to like /api/users?uid=123?

    We can surely override get_object() or get_queryset() or any other stuff like this:

    class UserAPIView(RetrieveUpdateDestroyAPIView,
    CreateAPIView):
    serializer_class = UserSerializer
    queryset = User.objects.all()

    def get_object(self) -> User:
    uid = self.request.query_params.get('uid', None)

    if uid is None or not uid.isdigit():
    raise Http404

    self.kwargs.update({self.lookup_field: int(uid)})

    return super().get_object()


    but it looks kind of ugly, isn't it? I believe there should be a better way of dealing with it..

    Continue reading...

Compartilhe esta Página