【问题标题】:How to get count of objects in a ManyToManyField with 'self' / its own model in django?如何在 Django 中使用“self”/它自己的模型获取 ManyToManyField 中的对象数?
【发布时间】:2021-04-17 07:11:40
【问题描述】:

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

【问题讨论】:

    标签: python django django-models orm many-to-many


    【解决方案1】:

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

    【讨论】:

    • 您是否注意到用户可以关注自己,如果您这样做了。你的解决方案是什么。
    猜你喜欢
    • 2013-06-11
    • 2013-06-08
    • 2021-10-30
    • 1970-01-01
    • 2021-04-04
    • 2011-03-24
    • 2021-02-14
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多