Search code examples
pythondjangodjango-rest-frameworkdjango-views

Object of type ListSerializer is not JSON serializable


I want to Serialize a Django model and Show it as a DRF Response and Im facing this error many times

here is my API view:

class ListCommentsApiView(APIView):
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.AllowAny]
    
    def get(self, request: HttpRequest) -> Response:
        comments = Comment.objects.all()
        serialized_comments = CommentModelSerializer(instance=comments, many=True)
        
        return Response(serialized_comments)

here is my model:

class Comment(models.Model):
    RATES: list[tuple[int, str]] = [
        (1, 'Worst'),
        (2, 'Meh'),
        (3, 'Best'),
    ]
    
    user = models.ForeignKey(to=User, default=None, blank=True, on_delete=models.CASCADE ,verbose_name='User')
    text = models.TextField(max_length=200, default=None, blank=True, verbose_name='Comment')
    rate = models.IntegerField(choices=RATES, default=None, blank=True, verbose_name='Rate')
    viewed_by_admin = models.BooleanField(default=False, blank=True, verbose_name='Viewed By Admin')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created at')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='Updated at')
    
    def __str__(self) -> str:
        return str(self.user)
    
    class Meta:
        verbose_name = 'Comment'
        verbose_name_plural = 'Comments'

here is my serializer:

from rest_framework import serializers

from comment.models import Comment




class CommentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = ['text', 'rate']

so I tried many things but it didn't work and I don't know what to do and I would appreciate a little help


Solution

  • You're not accessing the serialized data.

    Change

    serialized_comments = CommentModelSerializer(instance=comments, many=True)
    

    to

    serialized_comments = CommentModelSerializer(instance=comments, many=True).data