python / intermediate
Snippet
Django REST Framework Custom Serializers with SerializerMethodField
Custom serializers in Django REST Framework allow you to transform model data into JSON representations tailored to your API needs. The SerializerMethodField is particularly useful when you need to compute values that don't exist directly on the model, such as a user's full name combining first and last name, or aggregated data like article counts.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from rest_framework import serializersfrom django.contrib.auth.models import Userfrom .models import Articleclass AuthorSerializer(serializers.ModelSerializer):full_name = serializers.SerializerMethodField()article_count = serializers.SerializerMethodField()class Meta:model = Userfields = ['id', 'username', 'full_name', 'article_count']def get_full_name(self, obj):return f"{obj.first_name} {obj.last_name}".strip() or obj.usernamedef get_article_count(self, obj):return obj.articles.count()class ArticleSerializer(serializers.ModelSerializer):author = AuthorSerializer(read_only=True)tags = serializers.StringRelatedField(many=True)class Meta:model = Articlefields = ['id', 'title', 'content', 'author', 'tags', 'created_at']
django
Breakdown
1
from rest_framework import serializers
Import the serializers module from DRF to access ModelSerializer and custom field types
2
from django.contrib.auth.models import User
Import Django's built-in User model to serialize user data
3
full_name = serializers.SerializerMethodField()
Define a computed field that calls get_full_name method to combine first and last name
4
def get_full_name(self, obj):
Custom method receives the model instance as obj and returns computed value
5
return f"{obj.first_name} {obj.last_name}".strip() or obj.username
Format name safely, returning username if first/last name are empty
6
def get_article_count(self, obj):
Another SerializerMethodField that counts related articles via reverse relation
7
author = AuthorSerializer(read_only=True)
Nested serializer embeds full AuthorSerializer within ArticleSerializer for nested JSON output