Custom serializer fields let you control how data is converted when sending or receiving it in APIs. This helps handle special data types or formats easily.
Custom serializer fields in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
from rest_framework import serializers class MyCustomField(serializers.Field): def to_representation(self, value): # Convert the Python object to a simple data type return str(value) def to_internal_value(self, data): # Convert the input data back to the Python object return data
to_representation changes Python data to a format for the API response.
to_internal_value changes input data from the API to Python data.
Examples
Django
class UpperCaseField(serializers.Field): def to_representation(self, value): return value.upper() def to_internal_value(self, data): return data.lower()
Django
class BooleanStringField(serializers.Field): def to_representation(self, value): return 'yes' if value else 'no' def to_internal_value(self, data): return data.lower() == 'yes'
Sample Program
This example shows a custom field that converts a boolean to 'yes' or 'no' strings in the API. It also validates input to accept only 'yes' or 'no'.
Django
from rest_framework import serializers class YesNoBooleanField(serializers.Field): def to_representation(self, value): return 'yes' if value else 'no' def to_internal_value(self, data): if not isinstance(data, str) or data.lower() not in ('yes', 'no'): raise serializers.ValidationError('Must be "yes" or "no"') return data.lower() == 'yes' class ExampleSerializer(serializers.Serializer): active = YesNoBooleanField() # Example usage serializer = ExampleSerializer(data={'active': 'yes'}) serializer.is_valid(raise_exception=True) print(serializer.validated_data) print(serializer.data)
Important Notes
Always raise serializers.ValidationError in to_internal_value if input is invalid.
Custom fields help keep your API data clean and user-friendly.
Summary
Custom serializer fields let you control data format in APIs.
Use to_representation to change output data.
Use to_internal_value to validate and convert input data.
Practice
1. What is the main purpose of creating a custom serializer field in Django REST Framework?
easy
Solution
Step 1: Understand serializer fields role
Serializer fields define how data is transformed between Python objects and JSON.Step 2: Identify custom field purpose
Custom fields let you control this transformation, especially for special data formats.Final Answer:
To control how data is converted to and from JSON format -> Option DQuick Check:
Custom serializer fields = control data format [OK]
Hint: Custom fields change data format in API input/output [OK]
Common Mistakes:
- Confusing serializer fields with database models
- Thinking custom fields handle authentication
- Assuming styling is done in serializers
2. Which method should you override in a custom serializer field to change how data is shown in API responses?
easy
Solution
Step 1: Recall method roles in serializer fields
to_representationconverts Python data to JSON output;to_internal_valueconverts input JSON to Python.Step 2: Identify output formatting method
To change API response format, overrideto_representation.Final Answer:
to_representation -> Option BQuick Check:
Output formatting = to_representation [OK]
Hint: Output uses to_representation method [OK]
Common Mistakes:
- Using to_internal_value for output formatting
- Confusing validate with data conversion
- Overriding create instead of serialization methods
3. Given this custom serializer field code, what will be the output for input value 10?
class DoubleField(serializers.Field):
def to_representation(self, value):
return value * 2
field = DoubleField()
print(field.to_representation(10))medium
Solution
Step 1: Analyze to_representation method
The method multiplies the input value by 2 before returning it.Step 2: Calculate output for input 10
10 * 2 = 20, so the output is 20.Final Answer:
20 -> Option AQuick Check:
10 doubled = 20 [OK]
Hint: to_representation transforms output value [OK]
Common Mistakes:
- Expecting input unchanged
- Confusing output type as string
- Assuming method raises error
4. Identify the error in this custom serializer field code:
class UpperCaseField(serializers.Field):
def to_internal_value(self, data):
return data.upper()
field = UpperCaseField()
print(field.to_internal_value(None))medium
Solution
Step 1: Check method call on input
The code callsdata.upper()but data is None, which has no upper() method.Step 2: Identify error type
This causes an AttributeError at runtime.Final Answer:
Calling upper() on None causes an AttributeError -> Option CQuick Check:
None.upper() = AttributeError [OK]
Hint: Check input type before calling string methods [OK]
Common Mistakes:
- Assuming None is valid string input
- Thinking inheritance must be CharField
- Missing return statement (actually present)
5. You want to create a custom serializer field that accepts a comma-separated string of numbers and outputs a list of integers. Which methods should you override and how?
hard
Solution
Step 1: Understand input and output roles
Input is a string (comma-separated), soto_internal_valuemust parse it into a list of integers.Step 2: Format output for API response
to_representationshould convert the list back into a comma-separated string for output.Final Answer:
Override to_internal_value to split and convert input string; override to_representation to join list into string -> Option AQuick Check:
Input parsing = to_internal_value, output formatting = to_representation [OK]
Hint: Parse input in to_internal_value, format output in to_representation [OK]
Common Mistakes:
- Swapping input/output methods
- Using validate instead of conversion methods
- Overriding create/update which are unrelated
