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 :
from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
days_since_joined = serializers.SerializerMethodField()
model = User
def get_days_since_joined(self, obj):
return (now() - obj.date_joined).days
Here’s a preview of how I implemented it :
user_is_liking = serializers.SerializerMethodField()
def get_user_is_liking(self, obj):
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.