SQLAlchemy:TypeError在更新中使用比较运算符

时间:2019-01-03 21:20:59

标签: python postgresql sqlalchemy

我正在尝试在SQLAlchemy批量更新查询中执行比较。算术运算符可以工作,但是进行比较会导致模糊的TypeError。下面的基本示例有望突出显示该问题。

class Student(Base):
    __tablename__ = "students"
    id = Column(Integer, primary_key=True)
    score = Column(Integer, nullable=True)
    is_passing = Column(Boolean, nullable=True)

def is_passing(score, passing_score):
    if score >= passing_score:
        return True
    else:
        return False

def main():
    s = Session(engine)
    query = s.query(Student)  
    query.update(
            {
                "is_passing": is_passing(Student.score, 65.0)
            },
            synchronize_session=False,
       )

如果运行查询以构建更新值列表,我可以完成我需要做的事情,但是它不能解释错误。

updated_mappings = [{"id": row.id, "is_passing": is_passing(row.score, 65.0)}
                    for row in query]
s.bulk_update_mappings(Student, updated_mappings)

产生的错误消息:

<ipython-input-4-4914ec21fc1f> in is_passing(score, passing_score)
     41 
     42 def is_passing(score, passing_score):
---> 43     if score >= passing_score:
     44         return True
     45     else:    
~/Envs/pandas/lib/python3.6/site-packages/sqlalchemy/sql/elements.py in __bool__(self)
   2991             return self.operator(hash(self._orig[0]), hash(self._orig[1]))
   2992         else:
-> 2993             raise TypeError("Boolean value of this clause is not defined")
   2994 
   2995     __nonzero__ = __bool__

TypeError: Boolean value of this clause is not defined

0 个答案:

没有答案