Hamza
Hamza

Reputation: 1533

Django : Post counts per user in user's list

How to return the user's posted items from another model , as example I have model called Post ( with Author as foreign key to User's Auth Model ) . how to return list of users and number of Posts for each ? may be latest post for everyone in a list .

def users_list(request):
    users = UserProfile.objects.all()
    for userposts in users:
        posts_count = Post.objects.filter(author=users.user).count()
    return render_to_response('users.html',{'users':users,'posts_count':posts_count})

Upvotes: 1

Views: 1638

Answers (2)

jpic
jpic

Reputation: 33420

Example usage of annotate and Count:

for user in User.objects.annotate(post_count=Count('post')):
    print user.post_count

Generating aggregates for each item in a QuerySet:

Per-object summaries can be generated using the annotate() clause. When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values

Not to be confused with aggregate, Generating aggregates over a QuerySet:

What we need is a way to calculate summary values over the objects that belong to this QuerySet. This is done by appending an aggregate() clause onto the QuerySet

  • annotate(): aggregate per item of the queryset
  • aggregate(): aggregate all items of the queryset

Upvotes: 2

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53999

UserProfile.objects.all().annotate(num_posts=Count('post'))

Upvotes: 1

Related Questions