Learnlog

Learnlog

1151 bookmarks
Custom sorting
What is the benefit of using a HyperlinkedModelSerializer in DRF?
What is the benefit of using a HyperlinkedModelSerializer in DRF?
100View upvote and downvote totals. This answer is not useful Save this answer. Show activity on this post. We need to implement relationship between entities in Web API design. There are several ways to do that (as mentions on DRF documentation): Using primary keys. Using hyperlinking between entities. Using a unique identifying slug field on the related entity. Using the default string representation of the related entity. Nesting the related entity inside the parent representation. Some other custom representation The HyperlinkedModelSerializer has the following differences from ModelSerializer: It does not include the id field by default. It includes a url field, using HyperlinkedIdentityField. Relationships use HyperlinkedRelatedField, instead of PrimaryKeyRelatedField.
The benefit is that you will not have to construct resource URLs in your frontend when you want to retrieve related objects. Another thing entirely is nested representations which allows you to inline related objects in your serializer output. This can be combined with both ModelSerializer and HyperlinkedModelSerializer when you think that it is more convenient for the API consumer to have related items right away instead of making additional requests to retrieve them.
using hyperlinks in your resources will make it easier for any developer using your web API. If they can see the whole resource URI they won´t need any documentation or other ways to find that out
Easy solution to this is adding the 'id' field too in your serializer: id = serializers.ReadOnlyField()
·stackoverflow.com·
What is the benefit of using a HyperlinkedModelSerializer in DRF?