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

前端 未结 1 691
再見小時候
再見小時候 2021-02-14 04:58

Using a ModelViewSet, is it normal for get_serializer_class to be called multiple times for a single request, when accessing the browsable API? And tha

1条回答
  •  一整个雨季
    2021-02-14 05:30

    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.

    0 讨论(0)
提交回复
热议问题