[Solved]-Django Rest Framework: `get_serializer_class` called several times, with wrong value of request method

19👍

The reason why you are seeing get_serializer_class being called multiple times is because you are using the browsable API. If you test it out without using the browsable API, for example by forcing the JSON renderer (?format=json or an Accept header), you will only see it called one.

The browsable API generates the forms that are displayed based on the serializer, so get_serializer_class is called once for each form and possible request type.

So while the first request, a GET makes sense for the original serializer that is used to handle the response data (the specific object, in this case), the next three are custom to the browsable API. These are the calls that happen, in the following order, to get_serializer which you are seeing

  1. The raw PUT form (for entering any request body).
  2. The raw PATCH form.
  3. The full PUT form (contains the instance data by default).

The method is being changed with the override_method with function which emulates the request method being overridden, which would normally happen in a POST request that needed a different method.

Leave a comment