Serializers in Django REST Framework

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 provide deserialization, i.e. validating and then converting JSON data back into complex types.

Multiple SeriaizerMethodField() needs to access a same resource in Database. One easier way is to get the resource from DB at each get_<fieldname> method. It works fine but getting same resource again and again from DB is not 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.

Web Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store