Related Fields in Django REST Framework
DRF tip:
To represent model relationships in a serializer, you can use various related fields that represent the target of the relationship in different ways:
- StringRelatedField
- PrimaryKeyRelatedField
- HyperlinkedRelatedField
- SlugRelatedField
- HyperlinkedIdentityField
Examples:
class TagSerializer(serializers.ModelSerializer): posts = serializers.StringRelatedField(many=True) # result: "My story" (from __str__ method) posts = serializers.PrimaryKeyRelatedField(many=True, read_only=True) # result: 1 posts = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='post-detail' ) # result: "http://127.0.0.1:8000/1/" posts = serializers.SlugRelatedField( many=True, read_only=True, slug_field='title' ) # result: "My story" (from title field) tag_detail = serializers.HyperlinkedIdentityField(view_name='tag-detail') # result: "http://127.0.0.1:8000/tags/1/" # *HyperlinkedIdentityField is used for current object, not related objects
For more, review Serializer relations.