在restframework Django中添加many=True后属性错误?

2024-09-26 18:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

class CommentSerializer(serializers.ModelSerializer):


    class Meta:

        model = Comment
        fields=('Comment','Comment_text','Comment_time','Comment_Post','Comment_User', )

class PostSerializers(serializers.ModelSerializer):
    comment = CommentSerializer(many=True)

    class Meta:
    model = Postovo
    fields = ('Postovo_id','Postovo_trending','comment', )

模特都是这样的

^{pr2}$

下一个

class Comment(models.Model):

Comment = models.AutoField(primary_key=True)
Comment_text = models.CharField(max_length=100)
Comment_time = models.CharField(max_length=100,default=currentTimestamp)
Comment_Post = models.ForeignKey(Postovo, related_name='commentpost' ,default='1', editable=True)
Comment_User = models.ForeignKey(RegUser, related_name='commentuser' ,default='1', editable=True)
def __str__(self):
    return '%s' % (self.Comment)  

在视图中

class Postcomment(viewsets.ModelViewSet):

queryset = Postovo.objects.all()
serializer_class = PostSerializers

错误

AttributeError: Got AttributeError when attempting to get a value for field comment on serializer PostSerializers. The serializer field might be named incorrectly and not match any attribute or key on the Postovo instance. Original exception text was: 'Postovo' object has no attribute 'comment'.


Tags: texttruedefaultmodelmodelscommentmetaclass
1条回答
网友
1楼 · 发布于 2024-09-26 18:14:36

您需要使用相关名称commentpost,而不是PostSerializers中的comment。在

class PostSerializers(serializers.ModelSerializer):
    commentpost = CommentSerializer(many=True)

    class Meta:
    model = Postovo
    fields = ('Postovo_id','Postovo_trending','commentpost', )

出现错误是因为Postovo实例上没有comment属性。获取所有相关的Comment实例的管理器可以使用related_namecommentpost进行访问。在

相关问题 更多 >

    热门问题