我正在尝试创建一个支持任意数量的回复的评论模型。我正在使用Django Rest Framework,对于注释树,我正在使用django-treebeard。
这是我的模型代码:
class Comment(MP_Node):
paylasan = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
soru = models.ForeignKey(
to=Soru,
related_name="comments",
on_delete=models.CASCADE)
metin = models.TextField()
upvote = models.PositiveIntegerField(default=0)
downvote = models.PositiveIntegerField(default=0)
created = models.DateTimeField(auto_now_add=True)
node_order_by = ['upvote']
def __unicode__(self):
return self.metin
这是我的观点,很简单:
class Comments(generics.ListAPIView):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
这是我的序列化器:
class CommentSerializer(serializers.ModelSerializer):
paylasan = serializers.StringRelatedField()
children = serializers.SerializerMethodField(
read_only=True, method_name="get_children_nodes"
)
parent = serializers.SerializerMethodField(
read_only=True, method_name="get_parent_nodes"
)
class Meta:
fields = (
"id",
"metin",
"soru",
"paylasan",
"children",
"parent",
"upvote",
"downvote",
"created"
)
model = Comment
def get_children_nodes(self, obj):
child_queryset = obj.get_descendants()
return CommentSerializer(child_queryset, many=True).data
def get_parent_nodes(self, obj):
try:
parent_id = obj.get_parent().id
except AttributeError:
return {}
parent_queryset = Comment.objects.filter(id=parent_id)
return CommentSerializer(parent_queryset, many=True).data
当我在ipython shell中运行测试时,出现错误提示
RecursionError: maximum recursion depth exceeded while calling a Python object
最终指向序列化程序中的这些行:
~/Python/webapp/soruweb/serializers.py in get_children_nodes(self, obj)
82 def get_children_nodes(self, obj):
83 child_queryset = obj.get_descendants()
---> 84 return CommentSerializer(child_queryset, many=True).data
85
86 def get_parent_nodes(self, obj):
问题是,如何摆脱这个错误?
编辑:我忘了说的是,当我尝试仅包含子字段或父字段并注释其他字段时,它可以工作。但是当我将它们一起尝试时,将无法正常工作。