0

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?

SilentDev
  • 20,997
  • 28
  • 111
  • 214
  • 1
    You can do this by creating a function that returns the boolean that you want: http://stackoverflow.com/a/18426235/1913888 – Aaron Lelevier Nov 06 '15 at 02:05

1 Answers1

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
Anush Devendra
  • 5,285
  • 1
  • 32
  • 24
  • `usersVoted` is already a field in my serializer (it consists of a list of User objects) which I want to be sent to the frontend, so I cannot use the name ` usersVoted = serializers.SerializerMethodField()`. – SilentDev Nov 07 '15 at 00:36