While trying to serialize child and parent nodes of a model, I get RecursionError

I am trying to make a comment model that supports an arbitrary number of replies. I am using Django Rest Framework and for comment trees I am using django-treebeard.

This is my model code:

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

This is my view which is simple:

class Comments(generics.ListAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

This is my serializer:

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

When I run a test in ipython shell, I get an error saying RecursionError: maximum recursion depth exceeded while calling a Python object which eventually points to these lines in serializer:

~/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):

The question is, how do i get rid of this error?

Edit: What I forgot to say is that, when I try to contain only children or parent fields and comment the other one, it works. But when I try both of them together it does not work.

Upvotes: 1

Views: 841

Answers (0)

Related Questions