簡體   English   中英

如何在 Flask SQLAlchemy 中使用 SUM 聚合 function?

[英]How to use SUM aggregate function in Flask SQLAlchemy?

我有這些簡單的課程:

class Terminal(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    terminal_id = db.Column(db.String(100), nullable = False)

    statistics = db.relationship('TerminalStatistic', backref='observed_terminal', lazy='dynamic')


    def all_statistics(self) -> int:
        todayDate = datetime.now()
        if todayDate.day > 25:
            todayDate += datetime.timedelta(7)

        first_day_of_month = todayDate.replace(day=1)

        return self.statistics.query(func.sum(TerminalStatistic.cash)).filter(TerminalStatistic.collection_date >= first_day_of_month)

    def __repr__(self):
        return "Terminal('{0}','{1}')".format(self.address, self.date_last_online)

class TerminalStatistic(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    terminal_id = db.Column(db.Integer, db.ForeignKey('terminal.id'))
    collection_date = db.Column(db.DateTime, nullable = False)
    cash = db.Column(db.Integer, nullable = True)   

所以TerminalTerminalStatistic有關系。
現在我想總結all_statistics(self)中的所有統計信息,但出現錯誤:

return self.statistics.query(db.func.sum(TerminalStatistic.cash)).filter(TerminalStatistic.collection_date >= first_day_of_month)

AttributeError: 'AppenderBaseQuery' object has no attribute 'query'

如何在類中對 collections 進行函數查詢?

我找到了解決方案:

result = self.query.with_entities(db.func.sum(TerminalStatistic.cash).label("sum_statistics")).filter(
TerminalStatistic.terminal_id == self.terminal_id).first()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM