简体   繁体   English

使用 Flask 和 SQLAlchemy 返回存储在数据库中的 integer 变量的总和?

[英]Return total sum of integer variable stored in database using Flask and SQLAlchemy?

I am creating an app using Flask and SQLAlchemy to track scores on a test for users.我正在使用 Flask 和 SQLAlchemy 创建一个应用程序来跟踪用户的测试分数。 The User Model includes an Integer variable 'Score'.用户 Model 包括一个 Integer 变量“分数”。 I want to add up the scores of all my registered users to produce an average score, but I am very new to Flask and unsure how to achieve it.我想将所有注册用户的分数相加得出一个平均分数,但我对 Flask 很陌生,不确定如何实现。

models.py模型.py

class User(UserMixin, db.Model):
#...
score = db.Column(db.Integer(), default = 0)

I would like to add the scores of all the different users and assign this value to a variable which i can then print out in one of my templates.我想添加所有不同用户的分数并将这个值分配给一个变量,然后我可以在我的一个模板中打印出来。 I've tried everything I can think of but don't know how to iterate through the score of each user and then add that accumulatively to the total_score variable.我已经尝试了所有我能想到的方法,但不知道如何遍历每个用户的分数,然后将其累积添加到 total_score 变量中。

I have tried我努力了

total_score = User.query.filter_by(User.score).first()

But feel like I am way off with this.但感觉我离这个还很远。 Would really appreciate any help on this thanks!非常感谢您对此的任何帮助,谢谢!

To get a single value representing the average score of all your users you can do something like this:要获得代表所有用户平均得分的单个值,您可以执行以下操作:

total_score = db.session.query(db.func.avg(User.score)).scalar()

Then you can pass it to your template something like this:然后你可以将它传递给你的模板,如下所示:

@app.route("/")
def route_name():
    total_score = db.session.query(db.func.avg(User.score)).scalar()

    return render_template("your-template.html", total_score=total_score)

Using db.func.avg we take the average of the score column and scalar gives us a single value back.使用db.func.avg我们取score列的平均值, scalar给我们一个单一的值。

https://docs.sqlalchemy.org/en/13/core/functions.html https://docs.sqlalchemy.org/en/13/core/functions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM