首页 > 解决方案 > 如何在 django 中使用“self”/它自己的模型获取 ManyToManyField 中的对象数?

问题描述

我正在尝试实现一个用户可以在 django 中互相关注的网络,如下所示:

> class User(AbstractUser):
>     followings = models.ManyToManyField('self', related_name='followers', symmetrical=False)

因此该followings字段将包含用户关注的所有用户,并且我还希望能够访问该用户的所有关注者,因此related_name.

我的问题是,如果我有一个用户的用户名,我该如何查询以检索该用户对象,并附上其关注者数量和关注者数量的注释?这是我尝试过的:

data = User.objects.annotate(number_of_followers=Count('followers'), number_of_followings=Count('followings')).get(username=user)

对我来说似乎没问题,但不知何故,它显示的值与实际数据库中的实数不匹配,因为我已经使用 django 管理应用程序进行了检查。

标签: pythondjangodjango-modelsormmany-to-many

解决方案


事实证明,使用 annotate 组合多个聚合(在我的例子中是 Count)会产生错误的结果,如文档中所述:

https://docs.djangoproject.com/en/3.1/topics/db/aggregation/#combining-multiple-aggregations

幸运的是,我可以使用该distinct参数,因为我使用的是 Count。这是工作线:

data = User.objects.annotate(number_of_followers=Count('followers', distinct=True), number_of_followings=Count('followings', distinct=True)).get(username=user)

推荐阅读