Django按多对多对象排序 [英] django order by count of many to many object

查看:301
本文介绍了Django按多对多对象排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型:

  class Category(models.Model):
个问题= models.ManyToManyField( '问题',related_name = cat_question,空白=真)
cat_name = models.CharField(max_length = 50)
cat_description = models.CharField(max_length = 255)

def __unicode __(self):
return self.cat_name

在我看来,我有:

  top_categories = Category.objects.all()[:7]。 

我在模板中将其作为上下文传递。
我想按问题的数量对排名靠前的类别进行排序,例如,如果A类别的问题最多,那么它应该排在最前;如果B的问题最多,那么B。然后第二位,依此类推。 p>

like top_categories = Category.objects.all()。order_by(Count(question)



有帮助吗?

解决方案

注释类别带有问题数量的对象,然后按降序排列:

  from django.db.models import Count 

top_categories = Category.objects.annotate(q_count = Count('questions'))\
.order_by('-q_count')[:7]

,您可以在文档排序,更多关于aggreagate 备忘单


I have a model :

class Category(models.Model):
    questions = models.ManyToManyField('Question', related_name="cat_question", blank=True)
    cat_name = models.CharField(max_length=50)
    cat_description = models.CharField(max_length=255)

    def __unicode__(self):
        return self.cat_name

and in my view I have :

top_categories = Category.objects.all()[:7].

I am passing it as context in the template. I want to sort the top categories by the number of questions in it like if A category has most question then it should be in top and if B has most question then B. Then second most and so on..

like top_categories = Category.objects.all().order_by(Count(question)

Any help ?

解决方案

Annotate Category objects with the number of questions and then order by this number in descend order:

from django.db.models import Count

top_categories = Category.objects.annotate(q_count=Count('questions')) \
                                 .order_by('-q_count')[:7]

and you can look on the example in the doc order-by, more examples for aggreagate cheat-sheet

这篇关于Django按多对多对象排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆