python - Django聚合

标签 python django

关注个人资料模型:

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/

相关文章:

python - 如何在不删除双端队列的情况下获取它的第一个值?

python - 避免对 Pandas 进行重复操作

Django logger.error 不会将日志记录条目保存到 debug.log 文件中

python - 如何在 Django 中运行 FFMPEG 命令?

python - Apache2 错误日志。调用 'site.addsitedir()' 失败 '(null)' ,停止

python - Django 表单未保存到数据库

python - 尝试连接到 RabbitMQ 时出现 IncompatibleProtocolError

python - 无法使用 python 2.7 错误 1045 连接到 mySql

python - 在 Django 中进行单元测试时如何处理损坏的约束?

python - 如何在此代码 Python 中处理 ValueError?