python - Django 在注释中使用组进行计数

标签 python django

我有一个配置文件模型,其中包含与 Stock 相关的 ManyToMany 字段。在我的管理仪表板中,我试图显示每只股票所在的观察列表的数量。我的注释查询是:

qs.annotate(watchlist_count=Count('profile__watchlist__symbol'))

但它返回的结果不正确

以下是模型:

class Profile(models.Model):
    user = OneToOneField(User, on_delete=models.CASCADE)
    watchlist = ManyToManyField(Stock, blank=True)

    def __str__(self):
        return self.user.email


class Stock(models.Model):
    symbol = CharField(max_length=15, unique=True)
    name = CharField(max_length=100)
    category = CharField(max_length=30, choices=CATEGORY_CHOICES, blank=True)
    about = TextField(help_text='About this company')

    def __str__(self):
        return f'{self.symbol} - {self.name}'

等效的 SQL 查询是:

select stock_id, count(stock_id) from api_profile_watchlist group by stock_id;

我的注释查询出了什么问题?

最佳答案

您进行了太多联接。通过在多对多关系上加入两次,您会“炸毁”计数。

您可以简单地用 Stock 来计算监视列表的数量,其中:

from django.db.models import Count

Stock.objects.annotate(
    <b>watchlist_count=Count('profile')</b>
)

这有效,因为默认情况下 related_query_name=… [Django-doc]具有模型名称(或 related_name 如果您指定了)。所以你从 Stock 写的隐式关系至Profile (Profile 关系中 Stockwatchlist 的反向之一)是 profile (小写)。因此,我们要求 Django 对给定的 Stock 进行计数对象,与 Profile 的关系数.

关于python - Django 在注释中使用组进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58920110/

相关文章:

python - 从检查堆栈中获取完全限定的方法名称

Django:如果可能的话,将 CharField 转换为 Integer

python - 有人可以解释这个表达式 : a[len(a):] = [x] equivalent to list. append(x)

python - 这段代码有什么问题?我收到一个名称错误

python - 使用 Django 托管静态网站

python - Django - 通过 bool 运算对模型进行排序的最佳方式

django rest 框架在 View 中返回选定的字段

python - GtkAboutDialog 关闭按钮错误

使用 "pathlib.Path"寻址 BASE_DIR 时,django Pycharm 2020.2.2 无法解析静态文件

python - Django CBV继承: Overriding attributes