2014-01-16 40 views
1

我有一個名爲用戶的表作爲django中的自定義用戶模型。 我有另一個模型PortfolioProjectDetail它有一個ForeignKey關係到我的User模型。表結構是這樣的:如何在Django查詢中排序?

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) 

我想找到的用戶列表與上傳項目的最大數量或找到投資組合的最大數量的用戶列表。我如何才能找到按照ProjecDetailPortfolio的編號排序的用戶的排序列表?

+0

您正在尋找註解/匯聚。查看備忘單[文檔中的示例](https://docs.djangoproject.com/en/dev/topics/db/aggregation/#cheat-sheet)。 –

回答

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')