0
0
Djangoframework~5 mins

Custom serializer fields in Django

Choose your learning style9 modes available
Introduction

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.

You want to change how a date or time is shown in your API response.
You need to convert a complex object into a simple string or number for the API.
You want to validate or clean data in a special way before saving it.
You have a field that is not supported by default serializers and need to define how to handle it.
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
This field converts text to uppercase when sending data, and to lowercase when receiving data.
Django
class UpperCaseField(serializers.Field):
    def to_representation(self, value):
        return value.upper()

    def to_internal_value(self, data):
        return data.lower()
This field shows booleans as 'yes' or 'no' strings in the API.
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)
OutputSuccess
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.