开发者

Get 'popular categories' in django

i have 2 models Books and Categories and I'm wondering how i would get the top 10 categories by the amount of books they have in开发者_运维问答 them.

My model looks like this

class Book(models.Model):
    """(Book description)"""
    categories = models.ManyToManyField(Category)

class Category(models.Model):
    """(Topic description)"""
    name = models.CharField(blank=False, max_length=100)

Any help would be great,

Thanks.


Have a look at Aggregation and order-by in the Django documentation.

You should be able to do something like:

Category.objects.annotate(num_books=Count('book')).order_by('num_books')

This will give you a list of categories ordered by their popularity, and you can then display only the first (or last) ten using a slice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜