Python 如何定义混合表达式?

Python 如何定义混合表达式?,python,mysql,sqlalchemy,hybrid,Python,Mysql,Sqlalchemy,Hybrid,我有两门课,活动课和预订课。一个活动可以容纳多个预订 class Event(Base): __tablename__ = 'event' id = Column(Integer, primary_key=True) space = Column(Integer) class Booking(Base): __tablename_ = 'booking' id = Column(Integer, primary_key=True) event_i

我有两门课,活动课和预订课。一个活动可以容纳多个预订

class Event(Base):
    __tablename__ = 'event'
    id = Column(Integer, primary_key=True)
    space = Column(Integer)

class Booking(Base):
    __tablename_ = 'booking'
    id = Column(Integer, primary_key=True)
    event_id = Column(Integer, ForeignKey('event.id'))
    event = relationship('Event', backref=backref('bookings'))
现在,我想计算入住率,并决定购买活动类的混合物业,如下所示:

@hybrid_property
def occupancy(self):
    return float(len(self.bookings)) / float(self.space)
session.query(Event).filter(Event.occupany > 0.5)
在某些情况下,这很好,但当我希望能够根据占用情况进行过滤时,例如:

@hybrid_property
def occupancy(self):
    return float(len(self.bookings)) / float(self.space)
session.query(Event).filter(Event.occupany > 0.5)
如果执行此操作,则会出现以下错误:

TypeError: object of type 'InstrumentedAttribute' has no len()
因此,我意识到我可能需要一个混合表达式,并提出:

@occupancy.expression
def occupancy(cls):
    return func.count(select([Booking.id]).where(cls.id == Booking.event_id).label('occupancy')) / cls.space
但是,这会导致MySQL错误:

sqlalchemy.exc.ProgrammingError: (_mysql_exceptions.ProgrammingError) 
(1111, 'Invalid use of group function') [SQL: u'SELECT event.id AS 
event_id FROM event \nWHERE count((SELECT booking.id \nFROM booking 
\nWHERE event.id = booking.event_id)) / event.space > %s'] 
[parameters: (0.5,)]

如何构造混合表达式?还是有更好的方法来实现我的目标?

计数应该在计算机内部完成。当前查询试图将
count()
函数应用于封闭查询的WHERE子句中的子查询的结果集,而WHERE子句没有分组,因此您会得到错误,更不用说作为谓词的聚合函数属于HAVING子句。只需移动电话:

@occupancy.expression
def occupancy(cls):
    stmt = select([func.count(Booking.id)]).\
        where(cls.id == Booking.event_id).\
        label('occupancy')
    return stmt / cls.space

子查询中的计数,而不是封闭查询中的计数:
选择([func.Count(Booking.id)])。其中(…)…
。是!你的评论才是真正的答案。非常感谢。如果你把它写成真实的答案,我可以接受。