ListSerializer 类型的对象不可 JSON 序列化

问题描述 投票:0回答:1

我想序列化 Django 模型并将其显示为

DRF Response
,我多次遇到此错误

这是我的 API 视图:

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)

这是我的模型:

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'

这是我的序列化器:

from rest_framework import serializers

from comment.models import Comment




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

所以我尝试了很多方法,但没有成功,我不知道该怎么做,我会很感激一些帮助

python django api django-rest-framework django-views
1个回答
0
投票

您没有访问序列化数据

改变

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

serialized_comments = CommentModelSerializer(instance=comments, many=True).data
© www.soinside.com 2019 - 2024. All rights reserved.