鉴于这两个模型:
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 的字典,这意味着我必须循环遍历它并将配置文件对象列表放在一起。这是许多额外的查询,但仍然没有产生查询集。到那时,我不妨直接使用原始 SQL。在我这样做之前,有没有办法从 Profile 模型中做到这一点? ProfileViews 通过ForeignKey 字段相关,但Profile 模型并不知道这一点,所以我不确定如何将两者联系在一起。
顺便说一句,我意识到我可以将视图存储为配置文件模型上的属性,这可能就是我在这里所做的,但我仍然有兴趣学习如何更好地使用聚合函数。
ProfileViews 通过外键字段相关,但 Profile 模型并不知道这一点
Profile 模型实际上知道这一点。
您应该能够执行以下操作:
Profile.objects.all().annotate(count_views=Count('profileview__pk')).order_by('count_views')
Edit:在这里您可以找到有关跨关系查找的 Django 文档http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)