About django/restframework request

Viewed 44

This is my APIview:

class Comments(ListCreateAPIView):

   queryset = models.NewsComment.objects
   filter_backends = [CommentsFilterBackend]
   http_method_names = ["get", "post"]

   def get_serializer(self, *args, **kwargs):
      if self.request.method = "get":
          return Myserializer

I want to know why self.request can call the "method". Isn't it the encapsulated Request new object? The native request object is encapsulated in Request obj. Why can self.request call the request.method attrs?

1 Answers

The answer is in the source code of Request class, more specifically at the the __getattr__ method (line 410):

    def __getattr__(self, attr):
        """
        If an attribute does not exist on this instance, then we also attempt
        to proxy it to the underlying HttpRequest object.
        """
        try:
            return getattr(self._request, attr)
        except AttributeError:
            return self.__getattribute__(attr)

It's one of Python's "magic methods" and you can read more about it here.

Related