关注个人资料模型:
class FollowProfile(models.Model):
profile = models.ForeignKey('userdata.Profile')
following = models.ForeignKey('userdata.Profile', related_name='following')
class Meta:
unique_together = (('profile', 'following'),)
[...]
配置文件模型:
class Profile(models.Model):
country = models.CharField(max_length=100, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
user = models.OneToOneField(User)
[...]
我想要获取的示例数据如下:
profile id 1 - followed by 10 profiles, following 3 profiles
profile id 2 - followed by 5 profiles, following 6 profiles
profile id 3 - followed by 2 profiles, following 1 profiles
profile id 4 - followed by 8 profiles, following 0 profiles
[...]
profile id 1204 - followed by 1 profiles, following 3 profiles
我知道我可以尝试使用 Django 聚合工具,所以我尝试了:
>>> profiles = Profile.objects.annotate(num_follows=Count('followprofile')).order_by('-num_follows')[:3]
>>> for profile in pofiles:
... profile.num_follows
... profile.user.username
35
u'chica'
24
u'xxxxx'
11
u'yyyyy'
但这给了我每个个人资料的关注个人资料的数量。等于:
>>> FollowProfile.objects.filter(profile__user__username='chica').count()
35
我还想要每人关注的个人资料数量。等于:
>>> FollowProfile.objects.filter(following__user__username='chica').count()
11
我怎样才能建立电话来获取这些号码?
最佳答案
字段“following”的相关名称是following
,所以这应该有效:
profiles = Profile.objects.annotate(num_following=Count('following'))
关于python - Django聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21383596/