Jand
Jand

Reputation: 2727

Django how to count 10 most occurrences

I have this model:

class Liker(models.Model):
    pic = models.IntegerField()
    pic_owners = models.IntegerField()

I am wondering what is the most efficient queryset to find top 10 pic_owners, i.e. the pic_owners whose pics have been liked the most?

Upvotes: 1

Views: 572

Answers (1)

catavaran
catavaran

Reputation: 45575

You should use aggregation:

from django.db.models import Count
rating = Liker.objects.values('pic_owners') \
                      .annotate(Count('pic_owners')) \
                      .order_by('-pic_owners__count')[:10]

This query will return a list of dicts with two keys: 'pic_owners' and 'pic_owners__count'.

Upvotes: 2

Related Questions