[Django]-Count the number of posts by a user – django

6👍

Constructing the query

For a given user, you can count the posts with:

def count_posts_of(user):
    return Post.objects.filter(author=user).count()

We thus take the set of all Post objects, we .filter(..) that set such that the author should be the given user, and then we perform a .count() on it to count the numbers in that set.

Rendering for a specific view

In case we want this for a specific view, we can for example count the number of posts for the user that is logged in:

def num_post(request):
    num_post = Post.objects.filter(author=request.user).count()
    return render(request, 'some_template.html', {'num_post': num_post})

We now can access the variable in the template with {{ num_post }} and render it the way we want.

Leave a comment