1

I want to make a nested comment model for an android app and I am using Django Rest framework. I have defined two models Post and Comment as follow:

class Post(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    author = models.ForeignKey('CustomUser',on_delete=models.CASCADE, related_name="author")
    created_at = models.DateTimeField(auto_now=True, editable=False)
    tag = models.ForeignKey('Tag', on_delete=models.CASCADE, blank=True, null=True)

class Comment(models.Model):
    p_post = models.ForeignKey('Post', on_delete=models.CASCADE)
    description = models.TextField()
    author = models.ForeignKey('CustomUser', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True, editable=False)
    p_comment_id = models.ForeignKey('self', blank=True)
    is_anon = models.BooleanField(default=False)

What I am having problem is if I want to get the list of comments on app, so, how should I deal with it? I have following points in my head:

  1. I can not return the complete list of comments, as it will be a very long list
  2. So, how do I chose to restrict to return top 5 comments along with their top 5 child comments.
hardik24
  • 1,008
  • 1
  • 11
  • 34

1 Answers1

0

If you add related_name to p_post:

p_post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name="comments")

You will be able to loop through them like so:

for post in Post.objects.order_by('created_at').all()[0:5]:
    for comment in post.comments.order_by('created_at').all()[0:5]:
        print(comment.description) # do whatever you want with comment

Note: [0:5] for limiting to the top 5

You also will want to prefetch the comments when querying for posts: Post.objects.prefetch_related('comments')

Edit:

Reading your question again, I see that this is for an API response. I would look into rest_framework.serializers.ModelSerializer

class CommentSerialzier(serializers.ModelSerializer):
    class Meta:
        model = Comment

class PostSerializer(serializers.ModelSerializer):
    comments = CommentSerializer(many=True)
    class Meta:
        model = Post
Red Twoon
  • 685
  • 4
  • 14