Django – Query for posts along with it's number of replies?

Issue

So I’m trying to populate a news feed with posts of a certain category. Then I want to be able to display the number of replies on the post. The reason I’m confused on how to do this, is because I filtered through goals by category then I filtered all the posts associated with all those goals and now I have a list of a dictionary containing the post body and goal description and create date, but I’d like to also add in the number of replies and I’m not sure how to do this in an efficient way. Also I realize my way of doing things in the view.py is less than ideal so any suggestions would be great!

Model.py

class Post(AbstractBaseModel):
    creator_id = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="post_creator_id")
    goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE)
    body = models.CharField(max_length=511, validators=[MinLengthValidator(5)])
    hash_tags = models.ManyToManyField(HashTag)

class ReplyPost(AbstractBaseModel):
    creator_id = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="reply")
    post_id = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.CharField(max_length=250)

View.py

@api_view(['GET'])
def get_most_recent_posts_by_category(request, category, count):
    goals_list = list(Goal.objects.filter(category = category).values_list('uuid', flat=True))
    data = list(Post.objects.filter(goal_id__in=goals_list).order_by('created').values('body', 'goal_id__description', 'created'))
    data['goal_description'] = data['goal_id__description']
    data['post_body'] = data['body']
    del data['goal_description']
    del data['body']
    return JsonResponse(data, status=status.HTTP_200_OK)

Solution

You can use Count('replypost') to add the number of items:

from django.db.models import Count

data = list(
    Post.objects.filter(
        goal_id__in=goals_list
    ).order_by(
        'created'
    ).values(
        'body', 'goal_id__description', 'created', replies=Count('replypost')
    )
)

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published