[DRF]What are the benefits of using nested Serializers over separate resources?

Solution 1:

In general, I use nested serializers when I want an interface where model B is always read (or created) together with model A. An example of this would be a Pizza model with a many-to-many relationship to Topping.

You'd want to separate these into two models to achieve a normalized database model, but retrieving a pizza's information without its toppings wouldn't make sense.

A 'create' example might be UserCredentials and Profile. You might want to separate these for security reasons, but it wouldn't make sense to create UserCredentials without an attached Profile.

The advantage here is a less complex interface. On the client-side, you don't need to do complex chained requests. (Retrieve pizza, then retrieve toppings every single time.) It also reduces overhead on the server, because there is only one request.

There are some disadvantages though. I tend to steer away from nested serializers because:

  • When you also want to be able to retrieve/create these relationships separately, you'll need either two serializers, or one more complex serializer. This requires a lot of maintenance to keep everything working correctly.
  • You might end up with multiple layers of nested serializers, which make it harder to separate your API into clearly defined resources.
  • Performance is harder to control, because you can't apply pagination on the nested resource.