hannu40k
hannu40k

Reputation: 562

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

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()?

Upvotes: 0

Views: 353

Answers (1)

Linovia
Linovia

Reputation: 20986

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

Upvotes: 4

Related Questions