如何在sqlalchemy中使用条件运算符or_ with conditional if?

时间:2016-04-25 07:37:14

标签: python optimization sqlalchemy refactoring

现有代码段:

if sup_usr_only:
    query_ob = query_ob.filter(
        or_(
            and_(
                Department.id.in_(login_user.department_ids),  # logic is OK - checked.
                model.visibility == VISIBLE_DEPT
            ),

            and_(
                model.visibility == VISIBLE_COMPANY,
                model.company_id == login_user.company_id
            ))
    )
else:
    query_ob = query_ob.filter(
        or_(
            and_(
                Department.id.in_(login_user.department_ids),  # logic is OK - checked.
                model.visibility == VISIBLE_DEPT
            ),
            model.visibility == VISIBLE_GLOBAL,
            and_(
                model.visibility == VISIBLE_COMPANY,
                model.company_id == login_user.company_id
            ))
    )

如果有检查或任何其他优化的话,我可以在线方式最小化代码片段吗? 想要在下面做这个(这在语法上是错误的):

query_ob = query_ob.filter(
            or_(
                and_(
                    Department.id.in_(login_user.department_ids),
                    model.visibility == VISIBLE_DEPT
                ),
                model.visibility == VISIBLE_GLOBAL if not sup_usr_only,
                and_(
                    model.visibility == VISIBLE_COMPANY,
                    model.company_id == login_user.company_id
                ))
        )

1 个答案:

答案 0 :(得分:3)

您可以预先在列表中创建or_的参数,然后将其应用于or_()函数:

options = [
    and_(
        Department.id.in_(login_user.department_ids),
        model.visibility == VISIBLE_DEPT
    ),
    and_(
        model.visibility == VISIBLE_COMPANY,
        model.company_id == login_user.company_id
    )]

if not sup_usr_only:
    options.append(model.visibility == VISIBLE_GLOBAL)

query_ob = query_ob.filter(or_(*options))

对于数据库而言,OR语句中列出的选项的顺序并不重要,但如果您认为该订单对您的应用程序很重要,那么您也可以使用options.insert(1, model.visibility == VISIBLE_GLOBAL)。 / p>