gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:11:26 56 4
gpt4 key购买 nike

我正在创建一个 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/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com