I have a sqlalchemy (actually Flask-sqlalchemy hence all the db.*) and I would like to be able to sort my 'Things' by their average vote.value of the 'Votes' that they are related to. Votes have a value of 0 to 100.
Having run into the issue that sqlalchemy would like to translate the average_vote_value @attribute into sql and fails I find that I should probably be using hybrids:
However I just can't work out how that is done in this case. Can anyone help please?
class Thing(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
votes = db.relationship('Vote', backref='thing', lazy='dynamic')
@hybrid_property
def average_vote_value(self):
'''average of vote.values'''
values = [v.value for v in self.votes]
try:
return sum(scores) / len(values)
except ZeroDivisionError:
return 50 # the default value
average_vote_value.expression
def average_vote_value(cls):
pass ### help ###
class Vote(db.Model):
id = db.Column(db.Integer, primary_key=True)
thing_id = db.Column(db.Integer, db.ForeignKey('thing.id'))
value = db.Column(db.Float, default=50.0)