Reputation: 2136
Here is my serializer method field:
def get_is_user_to_user(self, obj):
return obj.to_user == self.context.get('request').user.id
I want the method to return a boolean value of True
if obj.to_user
which is a field in the corresponding model equals the request.user.id
. The method field at the moment always returns False
even when it should be returning True
.
How do I check if obj.to_user
is equal to the request.user.id
from the serializer method field?
Upvotes: 2
Views: 2618
Reputation: 1
You can define a method i user model then use at as a field
E.g.:
class User(AbstractUser):
def chechsomething(self):
if something :
return True
return False
Upvotes: 0
Reputation: 1
I used below Sample View
class CurrentUserView(APIView):
def get(self, request):
serializer = UserSerializer(request.user)
return Response({"user": serializer.data})
Upvotes: 0
Reputation: 2240
def get_is_user_to_user(self, obj):
return obj.to_user == self.context.get('request').user.id
I think your FK obj.to_user
is a User instance, you can not compare with self.context.get('request').user.id
.
Your code should:
def get_is_user_to_user(self, obj):
return obj.to_user.id == self.context.get('request').user.id
Or:
def get_is_user_to_user(self, obj):
return obj.to_user == self.context.get('request').user # Make sure you did not override request.user before.
Upvotes: 1