I'm using Python/Flask/SQLAlchemy. I have a class Contest which I want to sort by rating which is (tricky) the sum of its child (Side) properties. The formula for the rating is
leftside.score + len(leftside.votes) + rightside.score + len(leftside.votes)
Models:
class Contest(db.Model):
leftside_id = db.Column(db.Text, db.ForeignKey('sides.id'))
rightside_id = db.Column(db.Text, db.ForeignKey('sides.id'))
leftside = db.relationship("Side", foreign_keys=[leftside_id])
rightside = db.relationship("Side", foreign_keys=[rightside_id])
rating = #??? leftside.score + len(leftside.votes) + rightside.score + len(leftside.votes)
class Side(db.Model):
score = db.Column(db.Integer, default=0)
votes = db.relationship('SideVote')
class SideVote(db.Model):
side_id = db.Column(db.Text, db.ForeignKey('sides.id'))
side = db.relationship('Side')
I can write a raw SQL, but it will return simple list, but I need SQLAlchemy query
SELECT *, (
score
+ (SELECT COUNT(*) FROM sidevotes WHERE side_id = contests.leftside_id or side_id = contests.rightside_id)
) as Field
FROM contests, sides
WHERE contests.leftside_id = sides.id or contests.rightside_id = sides.id
ORDER BY Field DESC
So once again, I need to sort Contests by the formula written above, here I see 2 possible solutions:
Either create some hybrid_property/column_property
Or execute SQL and map it SQLAlchemy query so I can use this results