SQLAlchemy-TypeError:此子句的布尔值未定义

时间:2019-04-15 13:56:28

标签: python sqlalchemy

我正在创建一个python应用程序,该应用程序的数据库包含来自不同足球比赛的结果。

我希望模型根据resulthome_score字段的值设置其away_score字段。

我在Django上做了很多工作-但这次不是,因为它将成为一个简单的终端应用程序。如果是的话,我将使用下面的save方法中的一些代码将result方法子类化。

对于SQLAlchemy来说,我有点陌生,我以为@hybrid_property装饰器是我要实现的目标的良好代理。

但是,当我为此模型运行单元测试时,它在下一行失败 elif self.home_score > self.away_score:

,出现以下错误:

TypeError: Boolean value of this clause is not defined

我已经在下面添加了模型,有人知道我在做什么错吗?

class Match(Base):
    __tablename__ = 'matches'

    id = Column(Integer, primary_key=True)
    date = Column(Date, nullable=False)
    home_id = Column(Integer, ForeignKey('teams.id'))
    home = relationship(
        "Team", back_populates='home_matches', foreign_keys=[home_id]
    )
    away_id = Column(Integer, ForeignKey('teams.id'))
    away = relationship(
        "Team", back_populates='away_matches', foreign_keys=[away_id]
    )
    home_score = Column(Integer, nullable=False)
    away_score = Column(Integer, nullable=False)


    @hybrid_property
    def result(self):
        """ Set the match result, based on the team scores """
        if self.home_score == self.away_score:
            return 'draw'
        elif self.home_score > self.away_score:
            return 'home'
        elif self.home_score < self.away_score:
            return 'away'

1 个答案:

答案 0 :(得分:3)

在查询上下文中使用混合属性的想法是产生等效的SQL。对于某些简单表达式,相同的代码可同时用于两者,但如果不是,则必须分别定义表达式。在这种情况下,您可以使用SQL CASE表达式替换Python:

from sqlalchemy import case

...

@hybrid_property
def result(self):
    """ Set the match result, based on the team scores """
    if self.home_score == self.away_score:
        return 'draw'
    elif self.home_score > self.away_score:
        return 'home'
    elif self.home_score < self.away_score:
        return 'away'

@result.expression
def result(cls):
    """ Set the match result, based on the team scores """
    return case([(cls.home_score == cls.away_score, 'draw'),
                 (cls.home_score > cls.away_score, 'home')],
                else_='away')