API design to avoid multiple model serializers (DRF)

I'm coding my backend with Django and my API with DjangoRestFramework.

The thing is I'm wondering how to handle serializers in order not to have tons of them for a single model.

Considering a model that represents, let's say, an InventoryItem (such as a computer). This computer can be linked to a category, a supplier, a company, a contact within that company...

That makes relations to be serialized and it brings nested data into the returned Item. While I may need all these fields in a list view, I may not in the form view or in a kanban view. And if I want to, for instance, in the form view of a helpdesk ticket, have an autocomplete input component to link the ticket to that inventory item, I want only to have, let's say, the name of the Inventory Item, so returning a list of items with all the nested data would be a bit overkill since I need only its name.

And you could say :

Just make different serializers for the scenarios you need.

I'd end up with something like :

  • InventoryItemFormSerializer
  • InventoryItemListSerializer
  • InventoryItemInputSerializer (to be used for input components)

Also for listing Items i'd use a .../api/inventory/items endpoint with the InventoryItemListSerializer but for populating an input component I'd use the same endpoint in order not to duplicate endpoints. That means I have to do some kind of 'magic' to make user of one or another serializer?

  • How should we design endpoints/serializers not to provide too much datas and to avoid duplicating endpoints ?

I've thought about having a nested serializer and a basic one for "each" (when necessary) model and say 'never mind' if I have a bit too much fields in the serialized datas. But it's seems a bit limitating...

Thanks in advance for advices.

Back to Top