1๐
โ
You can add a read-only 'voted'
SerializerMethodField
to your serializer.
This will add a key voted
to the serialized representation of the object.
From the SerializerMethodField
docs:
It can be used to add any sort of data to the serialized
representation of your object.It should return whatever you want to be included in the serialized
representation of the object.
class LinkSerializer(serializers.ModelSerializer):
voted = serializers.SerializerMethodField(method_name='has_user_voted') # add a 'voted' field
class Meta:
model = Link
fields = ('id', 'href', 'title','voted')
read_only_fields = ('id', 'href', 'title', 'voted')
def has_user_voted(self, obj):
user = self.context['request'].user # get the request object from context
user_votes = UserVotes.objects.filter(user=user, link=obj)
if user_votes:
return True # return True if any user_votes object exists
return False # otherwise return False
๐คRahul Gupta
Source:stackexchange.com