跨反向关系的Django聚合 [英] Django Aggregation Across Reverse Relationship
问题描述
鉴于这两个模型:
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 列表:
I want to get all profiles sorted by total views. I can get a list of profile ids sorted by total views with:
ProfileView.objects.values('profile').annotate(Count('profile')).order_by('-profile__count')
但这只是个人资料 ID 的字典,这意味着我必须遍历它并将个人资料对象列表放在一起.这是一些额外的查询,但仍然不会导致 QuerySet.到那时,我还不如放弃原始 SQL.在我做之前,有没有办法从 Profile 模型中做到这一点?ProfileViews 通过 ForeignKey 字段关联,但 Profile 模型并不知道这一点,所以我不确定如何将两者联系在一起.
But that's just a dictionary of profile ids, which means I then have to loop over it and put together a list of profile objects. Which is a number of additional queries and still doesn't result in a QuerySet. At that point, I might as well drop to raw SQL. Before I do, is there a way to do this from the Profile model? ProfileViews are related via a ForeignKey field, but it's not as though the Profile model knows that, so I'm not sure how to tie the two together.
顺便说一句,我意识到我可以将视图作为属性存储在 Profile 模型上,这可能就是我在这里所做的,但我仍然对学习如何更好地使用聚合函数感兴趣.
As an aside, I realize I could just store views as a property on the Profile model and that may turn out to be what I do here, but I'm still interested in learning how to better use the Aggregation functions.
推荐答案
ProfileViews 通过 ForeignKey 字段关联,但 Profile 模型并不知道这一点
ProfileViews are related via a ForeignKey field, but it's not as though the Profile model knows that
Profile 模型确实知道这一点.您应该能够执行以下操作:
The Profile model actually does know that. You should be able to do something like:
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
Edit: Here you can find Django docs about lookups that span relationships http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships
这篇关于跨反向关系的Django聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!