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 :
1 2 3 4 5 6 7 8 9 10 11 12 |
from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): days_since_joined = serializers.SerializerMethodField() class Meta: model = User def get_days_since_joined(self, obj): return (now() - obj.date_joined).days |
Here’s a preview of how I implemented it :
1 2 3 4 5 |
class PostSerializer(serializers.ModelSerializer): user_is_liking = serializers.SerializerMethodField() def get_user_is_liking(self, obj): return obj.likers.filter(id=self._context.get('request').user.id).exists() |
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.