Why does retrieving a single resource execute serializer.to_representation() multiple times in Django REST framework?

喜欢而已 提交于 2019-12-12 04:59:39

问题


Lets say I have a model called Thingy, and there are 20 Thingies in my database. When I retrieve all Thingies, serializer.to_represenatation() is executed 20 times. This is good.

However, when I retrieve just a single Thingy from /api/thingies/1, I observe that serializer.to_representation() is executed four (4!!!) times.

Why does this happen, and how can I get away with just one call to to_representation()?


回答1:


That's because you are using the browsable API. JSON renderer will only call it once.

Browsable API needs several calls:

  1. for the result itself
  2. for the raw data tab when you can modify a resource through PUT
  3. for the raw data tab when you can modify a resource through PATCH
  4. for the HTML form tab


来源:https://stackoverflow.com/questions/46421437/why-does-retrieving-a-single-resource-execute-serializer-to-representation-mul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!