[Answered ]-Django Rest Framework fail on setting a new context to the serializer

1👍

This is not necessary and inefficient. You can just annotate with:

from django.db.models import Exists, OuterRef


class CommentView(viewsets.ModelViewSet):
    serializer_class = serializer.CommentSerializer

    def get_queryset(self):
        return Comment.objects.annotate(
            user_like=Exists(
                Like.objects.filter(
                    comment_id=OuterRef('pk'), user_id=self.request.user.pk
                )
            )
        ).prefetch_related('likes')

In the serializer we then add the user_like field:

class CommentSerializer(serializers.ModelSerializer):
    likes = CustomUserSerializer(many=True)
    user_like = serializers.BooleanField(read_only=True)

    class Meta:
        fields = ('likes',)
        model = models.Comment

Leave a comment