How to select, sum, group and order with an inner join in flask-sqlalchemy and output a "highscore list" with jinja2?

Viewed 21

i got two models:

class User(db.Model):
    __tablename__ = "User"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(200), nullable=False)
    earnings = db.relationship("Salary", backref=db.backref("earner", lazy=True))

    def __repr__(self):
        return "<User %r>" % self.name

class Salary(db.Model):
    __tablename__ = "Salary"

    id = db.Column(db.Integer, primary_key = True)
    userid = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
    earned = db.Column(db.Float, nullable=False)

    def __repr__(self):
        return "<Earned %r>" % self.earned

I tried to make a "highscore" list with flask-sqlalchmey, but seem to don´t get the syntax right. I got an SQL statement, which does what i want (i made the first version of the app as a CLI program with mysql.connector):

@app.route("/highscore")
def highscore():

    query = """
    SELECT User.name, SUM(Salary.earned)
    FROM User
    INNER JOIN Salary ON Salary.userid = User.id
    GROUP BY User.name
    ORDER BY Salary.earned DESC
    """
    result = db.engine.execute(query).fetchall()

    return render_template("highscore.html", users = result)

With this code and the code in the template:

{% for user in users %} 
    {{ loop.index }}. {{ user.name }} has made a total of {{ user[1] }} Euro pooping. <br>
{% endfor %}

i get the desired output on the website:

  1. elwo has made a total of 18.0 Euro pooping.
  2. test has made a total of 4.5 Euro pooping.

My question ist, how can i get the same result with an sql.alchemy class based request? I tried things like

db.session.query(User, Salary).join(Salary).all()
User.query(User.name).join(Salary.earned).all()

and many more variations. Some of which didn't work at all.

With the query "Users.query.all()" and then in the template with "user.earnings" i get a list of all earnings. But i can´t sum them.

0 Answers
Related