Fix your get_ methods with 5 lines of code.
Here's an example of SerializerMethodField
from the Django Rest Framework docs:
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
If this get_
stuff hurts your soul like it does to mine, there's simpler way to do this.
First, let's create a new Serializer Field.
class SerializerLambdaField ( SerializerMethodField ):
def bind (self, field_name, parent):
super (SerializerMethodField, self ).bind(field_name, parent)
def to_representation (self, data):
return self .method_name(data)
Now you can write the previous serializer like this:
class UserSerializer ( serializers . ModelSerializer ):
days_since_joined = SerializerLambdaField( lambda obj: (now() - obj.date_joined).days)
class Meta :
model = User
Enjoy!