Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a class Score with a column item_id and several fields having different scores types(score1, score2, score3...)all having integer values.

I need to write a query that takes the list of scores types and returns a list with objects having itemid and sum of the scores of all score types mentioned in the list alongside. I'm trying to do this using hybrid method but confused about how to write the query.

model.py

class Score(db.Model):

    __tablename__ = 'scores'

    item_id                     = db.Column(db.Integer(), primary_key=True)
    score1                      = db.Column(db.Integer(), nullable=False)
    score2                      = db.Column(db.Integer(), nullable=False)
    score3                      = db.Column(db.Integer(), nullable=False)
    score4                      = db.Column(db.Integer(), nullable=False)

    @hybrid_method
    def total_score(self, fields):
        ts = 0
        for field in fields : 
            ts = ts + self[field]
        return ts

controller.py

app.route('/scores', methods=['POST'])
def scores():
    fields = ['score1', 'score2']
    scores = Score.query.all().order_by('total_score')

Obviously this does not work. Could you please help me write the query, much thanks!

This is how I need to have the final output :

[{'item_id' : 'x1', 'total_score' : y1},{'item_id' : 'x2', 'total_score' : y2},{'item_id' : 'x3', 'total_score' : y3}, ...]
share|improve this question
up vote 1 down vote accepted

You need to create expression for hybrid_method

class Score(db.Model):
    __tablename__ = 'scores'
    item_id  = db.Column(db.Integer(), primary_key=True)
    score1 = db.Column(db.Integer(), nullable=False)
    score2 = db.Column(db.Integer(), nullable=False)
    score3 = db.Column(db.Integer(), nullable=False)
    score4 = db.Column(db.Integer(), nullable=False)

    @hybrid_method
    def total_score(self, fields):
        return sum(getattr(self, field) for field in fields)

    @total_score.expression
    def total_score(cls, fields):
        return sum(getattr(cls, field) for field in fields)


fields = ['score1', 'score2']
scores = db.session.query(Score.item_id, Score.total_score(fields).label('total_score')).order_by('total_score')
final_output = [score._asdict() for score in scores]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.