Django sort posts by comments count

Viewed 195

I have created two Django models namely Post and Comment.

class Post(models.Model):
    title = models.CharField(max_length=255)
    post = models.TextField()

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    comment = models.TextField()

I would like to show all the posts on the homepage and order them by comments count. please help to achieve it.

2 Answers

You can work with a .annotate(…) [Django-doc] and then .order_by(…) [Django-doc]:

from django.db.models import Count

Post.objects.annotate(
    ncomment=Count('comment')
).order_by('-ncomment')

Since you can work with .alias(…) [Django-doc] to prevent calculating this both as column and in the ORDER BY clause:

from django.db.models import Count

Post.objects.alias(
    ncomment=Count('comment')
).order_by('-ncomment')

If you thus for example work with a ListView, you override the queryset attribute with:

from django.views.generic import ListView

MyListView(ListView):
    queryset = ost.objects.alias(
        ncomment=Count('comment')
    ).order_by('-ncomment')

You can use Django's built-in annotation to sort by count.

For eg:

from django.db.models import Count

mydata = Comment.objects.annotate(count=Count('comment')).order_by('-count')
#you can replace 'comment' with your respective fieldname.
Related