Django ORM,检查m2m关系模型的附加字段之和是否等于100

mznpcxlj  于 2022-12-05  发布在  Go
关注(0)|答案(1)|浏览(120)

我想对这个关系进行检查,以确保所有票的权重总和为100。

class PortfolioTicker(models.Model):
    """
    Helper model for M2M relationship between Tickers and Portfolios
    """

    portfolio = models.ForeignKey(Portfolio, models.PROTECT, related_name="tickers")
    ticker = models.ForeignKey(Ticker, models.PROTECT)
    weight = models.FloatField(null=False)

    def __str__(self) -> str:
        return f"{self.portfolio} {self.ticker} {self.weight}"
k4emjkb1

k4emjkb11#

如果要为每个滚动条生成报表:

x = PortfolioTicker.objects.values('ticker').order_by('ticker').annotate(summa=Sum('weight')).annotate(hundert=Case(When(summa=100, then=True), default=False))

如果要检查给定的股票代码

PortfolioTicker.objects.filter(ticker=given_ticker).aggregate(summa=Sum('weight'))['summa']

相关问题