Django REST Framework - HyperlinkedRelatedField


DRF tip:

According to Roy T. Fielding, RESTful APIs should be driven by hypertext.

To represent the target of the relationship with a hyperlink, you can use HyperlinkedRelatedField in the serializer.

👇

# serializer:
class TagSerializer(serializers.ModelSerializer):
    posts = serializers.HyperlinkedRelatedField(
        many=True, read_only=True, view_name='post-detail'
    )

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

# result:
{
    "name": "Stories",
    "posts": [
        "http://127.0.0.1:8000/1/",
        "http://127.0.0.1:8000/2/"
    ]
}