Using a ModelViewSet
,这正常吗?get_serializer_class
在访问可浏览的 API 时,是否会针对单个请求多次调用?并且该值self.method.request
每次通话之间的变化?
我已经创建了一个小测试项目来展示行为 https://github.com/decibyte/drf-method-example. In project/example/views.py https://github.com/decibyte/drf-method-example/blob/master/project/example/views.py有一个ThingViewSet
与定制get_serializer_class
,打印当前的请求方法。
如果您启动服务器并导航到http://127.0.0.1:8000/things/1/ http://127.0.0.1:8000/things/1/,输出将类似于:
./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
清楚地,get_serializer_class
被调用 4 次,具有不同的值(GET
, PUT
, PATCH
, PUT
),虽然只有一个GET
请求被执行。
奇怪的是,如果您以 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
问题是最后一次调用的请求方法get_serializer_class
可浏览的 API 是PUT
(这显然是错误的GET
请求),然后我们最终为请求使用了错误的序列化器,因为不同的请求方法返回不同的序列化器,这是我们在现实生活项目中所做的(例如,用于读取和写入操作)。
任何人都可以阐明正在发生的事情吗?为什么是get_serializer_class
多次调用可浏览 API,但方法值错误?