python - SQLAlchemy - 类型错误 : Boolean value of this clause is not defined

标签 python sqlalchemy

我正在创建一个 Python 应用程序,它有一个包含不同足球比赛结果的数据库。

我希望模型根据 home_scoreaway_score 字段的值设置其 result 字段。

我使用 Django 进行了大量工作 - 但这次不是,因为它将成为一个简单的终端应用程序。如果我是,我会用下面的 result 方法中的一些代码对 save 方法进行子分类。

作为对 SQLAlchemy 的新手,我假设 @hybrid_property 装饰器是我试图实现的目标的良好代理。

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

错误如下:

TypeError:此子句的 bool 值未定义

我已经包含了下面的模型,有人知道我做错了什么吗?

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'

最佳答案

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

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')

关于python - SQLAlchemy - 类型错误 : Boolean value of this clause is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55690796/

相关文章:

python - 使用 Sqlalchemy 时 Session_scope 引发属性错误

python - 列中的最后一条记录,SQLALCHEMY

python - 将数据从数据库移动到另一个数据库时出错

mysql - 如何创建配置了 time_zone 的 mysql+pymysql 引擎?

python - 如何中断事件信息以进行记录

python - 在Python中优雅地求和命名的DataFrame列

python - 如何从张量中获取值

python - SQLAlchemy:从特定用户的favorite_series中检索所有剧集

javascript - 使用高速公路 python 发送 json

python - django1.8 在 url.py 中包含 url 的正则表达式