Performance: Custom serializer fields
This affects the speed of data serialization and deserialization during API responses and requests, impacting server response time and perceived page load speed.
Jump into concepts and practice - no test required
from django.db.models import Count class MySerializer(serializers.ModelSerializer): custom_field = serializers.IntegerField(read_only=True) class Meta: model = MyModel fields = ['id', 'name', 'custom_field'] # In the view or queryset, annotate the count to avoid extra queries queryset = MyModel.objects.annotate(custom_field=Count('relatedmodel'))
class MySerializer(serializers.ModelSerializer): custom_field = serializers.SerializerMethodField() def get_custom_field(self, obj): # Performs a database query for each object return RelatedModel.objects.filter(parent=obj).count() class Meta: model = MyModel fields = ['id', 'name', 'custom_field']
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| SerializerMethodField with DB queries per object | N/A (server-side) | N/A | N/A | [X] Bad |
| Pre-annotated field with IntegerField | N/A (server-side) | N/A | N/A | [OK] Good |
to_representation converts Python data to JSON output; to_internal_value converts input JSON to Python.to_representation.class DoubleField(serializers.Field):
def to_representation(self, value):
return value * 2
field = DoubleField()
print(field.to_representation(10))class UpperCaseField(serializers.Field):
def to_internal_value(self, data):
return data.upper()
field = UpperCaseField()
print(field.to_internal_value(None))data.upper() but data is None, which has no upper() method.to_internal_value must parse it into a list of integers.to_representation should convert the list back into a comma-separated string for output.