SilentDev
SilentDev

Reputation: 22747

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

Assume this is my serializer:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('post', 'usersVoted')
        read_only_fields = ('usersVoted',)

usersVoted is a ManyToManyField with the User model (default Django model). What I want to do is when posts are being serialized, I also want a boolean sent to the front end which returns True if the current user is in the set of users in usersVoted (and False otherwise). I'm using DRF's ViewSets for my view:

class PostViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions.
    """
    queryset = Post.objects.all()
    serializer_class = PostSerializer

Is there any way for me to do this?

Upvotes: 0

Views: 174

Answers (1)

Anush Devendra
Anush Devendra

Reputation: 5475

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

Upvotes: 1

Related Questions