At the end of the day, you need to think about how to get the desired result as an SQL query. You cannot think about it only in terms of "hybrid, python, properties", etc. Although we are going to use these methods to get the result, this is how SQL works, which leads us there. So let me use Postgresql, and it is built into the AVG function, which is available in most databases. We need to JOIN from Thing to Vote, and since you want to consider the case where Thing has no votes, LEFT OUTER JOIN. The hybrid expression is just the syntax helper for the SQL expression you need, but at the end of the day, you still need to specify the JOIN that SQL requires:
from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.ext.declarative import declarative_base Base= declarative_base() class Thing(Base): __tablename__ = 'thing' id = Column(Integer, primary_key=True) name = Column(String(80)) votes = 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(values) / len(values) except ZeroDivisionError: return 50
(minus echo):
[(u'thing3', 50.0), (u'thing1', 8.22222222222222), (u'thing2', 15.4)]
source share