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.
A simple example:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
bash> http -a admin:yourpassword http://127.0.0.1:8000/users/
"results": [
{
"email": "[email protected]",
"groups": [
"http://127.0.0.1:8000/groups/1/",
"http://127.0.0.1:8000/groups/2/"
],
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin"
}
]
But if you change
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
The result will be:
"results": [
{
"email": "[email protected]",
"groups": [
1,
2
],
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin"
}
]