python - Sqlalchemy 选择条件

标签 python sqlalchemy

我的表上有一个映射器,我想定义一个 column_property,无论实体是否具有某些属性,它都应该选择 True 或 False:

mapper( Person, persons_table, properties = {
    'administrator': column_property( 
        select( 
            [True if roles_table.c.is_admin or roles_table.c.id == 1 else False],
            roles_table.c.id == persons_table.c.role_id
        ).label( 'administrator' )
        )
} )

这是我能做的吗?我对这部分更感兴趣:[True if Roles_table.c.is_admin or Roles_table.c.id == 1 else False],它允许我根据条件为列设置一个值.

最佳答案

您的 SELECT 表达式实际上是一个 Python 表达式:

select([True if roles_table.c.is_admin or roles_table.c.id == 1 else False],
       roles_table.c.id == persons_table.c.role_id)

sqlalchemy.select() 会将其视为:

select([True], some_expression_object)

因为列对象 roles_table.c.is_admin 在 bool 上下文中将计算为 True。我完全不知道 SQLAlchemy 将如何解释这一点,但它肯定不会按您的预期工作。

您必须使用 sqlalchemy.sql.expression.case() 重写此表达式,以便它与纯 SQL 相对应。而不是 if ... else ...:

column_property(
    select([case([(roles_table.c.is_admin, 1),
                  (roles_table.c.id == 1, 1)], else_=0)],
           roles_table.c.id == persons_table.c.role_id))

但是,对于您的情况,可能有一个更简单的解决方案。 PersonRole 似乎有一种 N:1 关系(一个人只有一个角色)。我假设有一个 orm.relationship Person.role 来获取一个人的角色。

为什么不添加一个普通的 Python 属性:

class Person:
    # ...

    @property
    def administrator(self):
        return self.role and (self.role.is_admin or self.role.id == 1)

关于python - Sqlalchemy 选择条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7848573/

相关文章:

Python 3.3 解释器和一行问题(4 行语句工作正常......)

python - 从日志文件中提取唯一访问者列表

python - 来自 2d numpy 数组的加权随机采样

python - SQLAlchemy DateTime 时区

python - 在 SQLAlchemy 中使用 declarative_base 时,如何在需要时绑定(bind)引擎?

python - 替代列表理解

python - Python 与 R 中的二项式检验

python - 数据库列的混合内容(float || unicode)

python - SQLAlchemy 通用关系简单示例

python - SQLAlchemy 中的 conn.execute ('some string' ) 和 conn.execute(text ('some string' )) 有什么区别?