如何在django查询中排序?

时间:2014-01-16 15:02:06

标签: python django django-queryset

我在django中有一个名为User的表作为自定义用户模型。 我有另一个名为PortfolioProjectDetail的模型与ForeignKey模型有User关系。表结构如下:

class ProjectDetail(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.TextField()
    category = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
    description = models.TextField(null=True, blank=True)
    vote_count = models.IntegerField(default=0) 

class Portfolio(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    project = models.ForeignKey(ProjectDetail, null=True, blank=True)
    description = models.TextField(null=True, blank=True)

和用户模型:

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(_('Username'), unique=True, max_length=100, blank=False, null=False,
        help_text=_('20 characters or fewer. Letters, numbers and -/_ characters, no capitals, no spaces'),
    )
    first_name = models.CharField(_('First Name'), max_length=30, blank=True, null=True)
    middle_name = models.CharField(_('Middle Name'), max_length=30, blank=True, null=True)
    last_name = models.CharField(_('Last Name'), max_length=30, blank=True, null=True)
    about_yourself = models.TextField(null=True, blank=True)

我想查找具有最大上传项目数的用户列表,或查找具有最大投资组合数的用户列表。如何找到按ProjecDetail的数量或Portfolio的数量排序的已排序用户列表?

1 个答案:

答案 0 :(得分:2)

使用annotate分组:

from django.db.models import Count

#group by portfolios count
User.objects.annotate(portfolios=Count('portfolio')).order_by('portfolios')
#group by projects count
User.objects.annotate(projects=Count('portfolio__project')).order_by('projects')