围绕Flask SqlAlchemy查询简化一对if-else语句

时间:2019-05-18 15:50:54

标签: python sqlalchemy

我的查询:

       if current_user['idx'] == 1:
            groups = sess.query(
            Role
            ).filter(
                ~Role.name.in_(codes.group1) # filtering
            ).order_by(
                Role.name
            )
        else:
            groups = sess.query(
            Role
            ).filter(
                ~Role.name.in_(codes.group2) # filtering
            ).order_by(
                Role.name
            )

我的代码文件:

group1= ['User']
group2 = ['Admin', 'User']

在上述查询中,我使用 codes.group1 语句下的if codes.group2下的else进行过滤。由于代码的查询部分看起来是重复的,是否有任何方法可以使代码在不重复的情况下更具可读性和简洁性?

2 个答案:

答案 0 :(得分:3)

由于查询几乎相同,因此您可以执行以下操作:

normal_user = current_user['idx'] == 1
groups = sess.query(
    Role
).filter(
    ~Role.name.in_(codes.group1 if normal_user else codes.group2)
).order_by(
    Role.name
)

group = codes.group1 if current_user['idx'] == 1 else codes.group2
groups = sess.query(
    Role
).filter(
    ~Role.name.in_(group)
).order_by(
    Role.name
)

答案 1 :(得分:2)

您可以像这样逐步创建查询:

groups = sess.query(Role)

if current_user['idx'] == 1:
    groups = groups.filter(~Role.name.in_(codes.group1))
else:
    groups = groups.filter(~Role.name.in_(codes.group2))

groups = groups.order_by(Role.name)