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 that the value of self.method.request
changes between each call?
I've created a small test project to show the behaviour. In project/example/views.py
there's a ThingViewSet
with a custom get_serializer_class
, which prints the current request method.
If you start the server and navigate to http://127.0.0.1:8000/things/1/, the output will be something like:
./manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
May 19, 2015 - 08:51:34
Django version 1.8.1, using settings 'project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Method is: GET
Method is: PUT
Method is: PATCH
Method is: PUT
[19/May/2015 08:51:40]"GET /things/1/ HTTP/1.1" 200 11679
Clearly, get_serializer_class
is called 4 times, with different values (GET
, PUT
, PATCH
, PUT
), although only a single GET
request is performed.
Strange thing is, that this doesn't happen if you request it as JSON:
./manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
May 19, 2015 - 10:25:57
Django version 1.8.1, using settings 'project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Method is: GET
[19/May/2015 10:26:22]"GET /things/?format=json HTTP/1.1" 200 49
And the problem is that the request method in the last call to get_serializer_class
of the browsable API is PUT
(which is obviously wrong for a GET
request) and then we end up using the wrong serializer for the request, given that different serializers are returned for different request methods, which we do in our real life project (e.g. for read and write operations).
Can anybody shed some light on what is going on? Why is get_serializer_class
called several times for the browsable API, with wrong method values?