我有一个配置文件模型,其中包含与 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
关系中 Stock
到 watchlist
的反向之一)是 profile
(小写)。因此,我们要求 Django 对给定的 Stock
进行计数对象,与 Profile
的关系数.
关于python - Django 在注释中使用组进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58920110/