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)
我想获取所有配置文件按总体视图排序。我可以通过以下方式获取总体视图排列的配置文件列表:
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。在我做之前,有没有办法从配置文件模型中做到这一点? 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
配置文件模型确实知道。
你应该可以这样做:
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屋!