Django REST Framework : add an attribute on the fly in a Serializer

Seralizers from DRF are doing a very good job at converting any Model to JSON data. They are even more awesome when you know how to add custom attributes to them.

In my case, I needed to add an attribute based on the current logged in user and related data from my model. To do that, I used a SerializerMethodField.

From the doc :

This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.

And the example :

Here’s a preview of how I implemented it :

Basically, this sets a field to True or False if the current user is ‘liking’ the Post object.

This is a pretty neat feature that I don’t want to forget about, so that’s why I’m writing it down here.

Published by


Web developer, geek, car enthusiast, photographer, DIYer, video gamer... I like many things, maybe too many?

Leave a Reply

Your email address will not be published. Required fields are marked *