我正在创建一个 python 应用程序,其中包含一个数据库,其中包含不同足球比赛的结果。
我希望模型根据和字段result的值设置其字段。home_scoreaway_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'
Run Code Online (Sandbox Code Playgroud)
混合属性的想法是在查询上下文中使用时生成等效的 SQL。对于某些简单的表达式,相同的代码适用于两者,但如果不是,则必须单独定义表达式。在这种情况下,您可以将 Python 替换为 SQLCASE表达式:
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13108 次 |
| 最近记录: |