[Answered ]-How to count and filter object in Django template?

1👍

You can .annotate(…) [Django-doc] with:

from django.db.models import Sum

def index(request):
    posts = Post.objects.annotate(
        number_of_likes=Count('like')
    ).order_by('-date')

    paginator = Paginator(posts, 10)

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'network/index.html', {
        'post_form': PostForm(),
        'posts': page_obj
    })

The Post objects that arise from this QuerySet will have an extra attribute .number_of_likes, so you render this with:

{%for post in posts.qs %}
    <a id="like_{{post.id}}" href="" class="like-link text-muted">+{{ post.number_of_likes }}</a>
{% endfor %}

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: Please do not name a variable list, it overrides the reference to the list builtin function [Python-doc]. Use for example posts.


Note: Section 9 of the HTTP protocol
specifies that requests like GET and HEAD should not have side-effects, so you
should not change entities with a simple link (with <a href="…">…</a> tags).
Normally POST, PUT, PATCH, and DELETE requests are used for this. In that case you make a small <form> that
will trigger a POST request, or you use some AJAX calls.

Leave a comment