Django REST Framework - HyperlinkedIdentityField


DRF tip:

To include a hyperlink that points to the current object in the serializer, you can use HyperlinkedIdentityField.

HyperlinkedIdentityField extends HyperlinkedRelatedField. Additionally, it makes the field read-only and sets the current object as the source.

👇

# serializer:
class TagSerializer(serializers.ModelSerializer):
    tag_detail = serializers.HyperlinkedIdentityField(view_name='tag-detail')

    class Meta:
        model = Tag
        fields = ['name', 'tag_detail']

# result:
{
    "name": "Stories",
    "tag_detail": "http://127.0.0.1:8000/tags/1/"
}