2010-05-04 77 views
7

鑑於這兩種模式:Django的聚集跨越反向關係

class Profile(models.Model): 
    user = models.ForeignKey(User, unique=True, verbose_name=_('user')) 
    about = models.TextField(_('about'), blank=True) 
    zip = models.CharField(max_length=10, verbose_name='zip code', blank=True) 
    website = models.URLField(_('website'), blank=True, verify_exists=False) 

class ProfileView(models.Model): 
    profile = models.ForeignKey(Profile) 
    viewer = models.ForeignKey(User, blank=True, null=True) 
    created = models.DateTimeField(auto_now_add=True) 

我想通過總的觀點排序的所有配置文件。我可以通過總的觀點與分類簡介ID列表:

ProfileView.objects.values('profile').annotate(Count('profile')).order_by('-profile__count') 

但是,這只是一個簡檔ID的字典,這意味着以後我就遍歷它放在一起輪廓對象的列表。這是多個附加查詢並且仍然不會導致QuerySet。那時候,我可能會掉到原始的SQL。在我做之前,有沒有一種方法可以從Profile模型中執行此操作? ProfileView通過一個ForeignKey字段相關,但它不像Profile模型知道的那樣,所以我不知道如何將兩者結合在一起。另外,我意識到我可以將Profile視圖的屬性存儲在Profile模型中,這可能會成爲我在這裏做的,但我仍然對如何更好地使用聚合函數感興趣。

回答

9

ProfileViews通過一個ForeignKey區域關聯,但就好像剖面模型的人都知道

的剖面模型實際上不知道,事實並非如此。 你應該能夠做一些事情,如:

Profile.objects.all().annotate(count_views=Count('profileview__pk')).order_by('count_views') 

編輯:在這裏你可以找到有關跨關係查詢Django文檔http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

+0

'from django.db.models import Count' – juanjo 2017-01-09 16:48:21

3

這肯定會工作:

Profile.objects.all().annotate(viewcount=Count('profileview')).order_by('-viewcount') 

由於Botondus說,Profile模型知道向後的ForeignKey關係。