Serializers in Django REST Framework

Bibhuti Poudyal
January 10, 2021
1 minute min read
Serializers allow complex data like database query results and model instances to be converted to native Python data types which can then be easily rendered into JSON content types. It also provides deserialization, i.e. validating and then converting JSON data back into complex types. Multiple SeriaizerMethodField() needs to access the same resource in the Database. […]

Serializers allow complex data like database query results and model instances to be converted to native Python data types which can then be easily rendered into JSON content types. It also provides deserialization, i.e. validating and then converting JSON data back into complex types.

Multiple SeriaizerMethodField() needs to access the same resource in the Database. One easier way is to get the resource from DB at each get_<fieldname> method. It works fine but getting the same resource again and again from DB is not the performant solution. Instead, a “get_resource” function can be written to access the resource once and use it throughout the serializer. At each get_<fieldname> method existence of the resource is checked. If found it is used else the “get_resource” function is called.

Here, the ‘get_translation’ function gets the resource i.e. ‘translation’. Other methods ‘get_title’, ‘get_slug’ and ‘get_excerpt’ uses the method to the share common resource.