How to Order Objects with Django REST Framework's Nested Serializer

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!

Freddie Freddie 2 years, 7 months ago 0
Login to Comment
No comments have been posted yet, be the first one to comment.
Query your Django REST API like a GraphQL API with Django RESTQL
Query your Django REST API like a GraphQL API with Django RESTQL
The hype around GraphQL in recent years has been hard to ignore for any web developer. In short, GraphQL is a query language and runtime for APIs, and it has taken the web with storm. GraphQL makes it possible for front-end developers to query data from a single API endpoint and retri...
How to Cache Django REST Framework with Redis
How to Cache Django REST Framework with Redis
Django REST Framework is an awesome package that will aid you in writing REST APIs faster with Django and Python. Though Django REST Framework has many strengths, performance out-of-the-box might not be one of them. However, there are many ways to fix that, and one of them is caching....
How to Rebuild Django-MPTT Tree Structure
How to Rebuild Django-MPTT Tree Structure
Most application utilize some sort of tree structure to managing data, in one form or another. One common use-case is nested categories. If you are using Django for your current project and are in need to implement tree structures, there is a big change you have come across Django-MPT...