Last Updated: September 27, 2021
·
1.589K
· oscarcp

Get most commented posts on django with django comments framework

posts_by_score = Comment.objects \
               .filter(is_public=True)
               .values('object_pk')
               .annotate(score=Count('id'))
               .order_by('-score')
post_ids = [int(obj['object_pk']) for obj in posts_by_score]
top_posts = Post.objects.filter(space=place.id).in_bulk(post_ids)

context['most_commented'] = top_posts

You will have to replace the Post filter with your own filtering criteria, but that's the easiest way I found to get the most commented posts with the django comments framework.