python - 如何在 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 管理应用程序进行了检查。
解决方案
事实证明,使用 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)
推荐阅读
- jquery - $("button").trigger("click") 似乎无法正常工作
- javascript - 使用 Javascript 调用 Chrome DevTools 命令
- python - 我正在尝试多次运行随机变量
- android - 使用 android-beacon-library 检测信标不起作用
- macos - SwiftUI 滚动视图部分显示 Mac 应用程序中的最后一项
- javascript - 在使用 selenium 抓取另一个网站的同时在烧瓶 Web 应用程序中加载页面
- javascript - 只允许预先验证的用户登录 Firebase
- c# - 使用 textchanged 函数以编程方式添加文本框
- javascript - 为什么我的 var 返回 NaN 而不是 html 结构?
- python - 如何使用来自 Bootstrap 模式的 jquery.ajax 发送复选框值?