I am using Django DRF, and having difficulty in applying SerializerMethodField (https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield)
Following is a simple case of typical model, serializer code, which works perfectly.
serializer.py (before)
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
view.py (before)
@api_view(['GET'])
def GetAllUsers(request):
Users = User.objects.all()
serializer = UserSerializer(Users, many=True)
return Response(serializer.data)
In order to deliver additional information which is not included in the model, I changed serializer
serializer.py (after)
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
Now I have to find a way to give obj(which has date_joined inside) to serializer, and I think I have to do it in view.py
But I don't know how to do it.
Thanks
objis the instance of the model and it is passed by the serializer to the method. What do you want to do exactly? Is theobjyou speak of not theUserinstance whosedate_joinedyou want to use? - Abdul Aziz Barkatget_days_since_joinedthat would be done by the serializer) - Abdul Aziz Barkat