[Fixed]-DjangoRestFramework – How to create a Serializer ReadOnlyField who's value depends on the user?

1👍

Yes you can do like:

class PostSerializer(serializers.ModelSerializer):
    userexists = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('post', 'usersVoted','userexists')
        read_only_fields = ('usersVoted','userexists')

    def get_userexists(self, obj):
        if self.context['request'].user in obj.usersVoted.all():
            return True
        else:
            return False

Leave a comment