Reputation: 11
first time here, so please be nice (?
I want to be able to show a Top X of most commented posts in the index of my website.
#models.py
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
text = models.TextField()
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
author = models.ForeignKey("auth.User", on_delete=models.CASCADE)
text = models.TextField()
#views.py
def index(request):
top_comm = #I know it has to be Django aggregation, but I can't make it.
return render(request, 'home/index.html', {"top_comm" : top_comm})
#index.html
{% for row in top_comm %}
{{row.author|linebreaksbr}}
{{row.text|linebreaksbr}}
{% endfor %}
Upvotes: 1
Views: 35
Reputation: 691
I might have misunderstood, but I think you want .annotate().
from django.db.models import Count
TOP_POST_LIMIT = 10
def index(request):
top_comm = Post.objects.annotate(c_count=Count('comment')).order_by('-c_count')[:TOP_POST_LIMIT]
return render(request, 'home/index.html', {"top_comm" : top_comm})
Upvotes: 1