How to Order Objects with Django REST Framework's Nested Serializer
An important part of building solid API is to utilize the power of nesting. With Django, and Django REST Framework its super easy to do so. But what if you want to order and manipulate these objects?
One powerful feature of Django REST Framework is ability to nest objects with serializers.
class PlayerSerializer(serializers.ModelSerializer):
class Meta:
model = Player
fields = ('name', 'number', 'position')
class TeamSerializer(serializers.ModelSerializer):
#nest the players inside of the team
players = PlayerSerializer(many=True, read_only=True,)
class Meta:
model = Team
fields = ('team_name', 'team_slogan', 'players')
It is that easy to nest your objects under other serializers. The only drawback with this is that you can not order or manipulate and of the objects that has been nested.
To do that we need to user a SerializerMethodField. With this field you can do pretty much anything that you have been accustomed to when using Django thus far.
Let me show you how to use SerializerMethodField to order your nested objects.
class TeamSerializer(serializers.ModelSerializer):
players = SerializerMethodField()
class Meta:
model = Team
fields = ('team_name', 'team_slogan', 'players')
#get players with a MethodField and order them by title
def get_players(self, instance):
players = instance.players.order_by('title')
return PlayerSerializer(players, many=True).data
As you can see we don't have to specify a method name in the SerializerMethodField because we name the mothod the same as the SerializerMethodField.
If we for example named our method get_players_related_to_team we would have to do so.
players = SerializerMethodField(method_name=players_related_to_team)
def get_players_related_to_team(self, instance):
players = instance.players.order_by('title')
return PlayerSerializer(players, many=True).data
In some cases it is necessary to do so because of the amount of methods specified for a specific serialiser would cause a collision.
Hope you found the tutorials useful!