Django Rest Framework Nested Comments

Viewed 303

i am trying to create a backend for blog website. I created a comment model and i have associated with blog post it. When I list the comments, I can also list the answers that have been made to the comment. But there is a problem that even though it appears in the comment as an answer, it also looks like it was the main comment again. How can I solve this. I would appreciate it if someone could help. I may have mistakes in English, I hope I was able to tell you what I wanted to tell you. Thanks in advance.

https://i.stack.imgur.com/HcEoT.png

Comment Model:

class Comments(models.Model):
      class Meta:
            verbose_name = 'Yorum'
            verbose_name_plural = 'Yorumlar'

      user = models.ForeignKey(User, verbose_name='Yorum sahibi', on_delete=models.CASCADE)
      post = models.ForeignKey(Post, verbose_name='Yorum yapılacak Post', on_delete=models.CASCADE,related_name='comments')
      parent_id = models.ForeignKey('self', verbose_name='Parent Yorum', related_name='subcomments',on_delete=models.CASCADE, null=True, blank=True)
      comment = models.TextField(verbose_name='Yorum')
      [enter image description here][1]created_at = models.DateTimeField(auto_now_add=True, blank=True)
      updated_at = models.DateTimeField(auto_now=True, blank=True)

    def __str__(self):
        return self.user.first_name + " " + self.user.last_name + " | " + self.post.title

Comment Serializer:

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
         model = Comments
         fields = '__all__'

    def get_fields(self):
         fields = super(CommentSerializer, self).get_fields()
         fields['subcomments'] = CommentSerializer(many=True, read_only=True)
         return fields

Post Serializer

class PostSerializer(serializers.ModelSerializer):
     tag = serializers.StringRelatedField(many=True, read_only=True)
     comments = CommentSerializer(many=True, read_only=True)
     author = AuthorSerializer(read_only=True)
     category = CategorySerializer2(read_only=True)

     class Meta:
        model = Post
        fields = '__all__'
1 Answers

First Option

You can use a nested serializer to solve your problem

class CommentSerializer(serializers.ModelSerializer):
    parent_id = serializers.PrimaryKeyRelatedField()

    class Meta:
        model = Comment
        fields = '__all__'

        def get_related_field(self, model_field):
            return CommentSerializer()

Second Option

You can use a library called djangorestframework-recursive for your use case

First, install the library

pip install djangorestframework-recursive

In your serializer file

from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField

class CommentSerializer(serializers.ModelSerializer):
    parent_id = serializers.ListField(child=RecursiveField())
    class Meta:
         model = Comments
         fields = '__all__'
Related