Kliver Max
Kliver Max

Reputation: 5299

How to use SUM aggregate function in Flask SQLAlchemy?

I hava thos simple classes:

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)   

So Terminal has relationship with TerminalStatistic.
Now i want to sum all statistics in all_statistics(self) but got error:

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

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

How to make queries with functions to collections in classes?

Upvotes: 2

Views: 1390

Answers (1)

Kliver Max
Kliver Max

Reputation: 5299

I found solution:

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

Upvotes: 2

Related Questions