如何在 Django 中使用 'self'/它自己的模型获取 ManyToManyField 中的对象数?

How to get count of objects in a ManyToManyField with 'self' / its own model in django?

我正在尝试实现一个用户可以在 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 管理应用程序检查的那样。

事实证明,使用 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)