python - How to use conditional operator or_ in sqlalchemy with conditional if? -


existing code snippet:

if sup_usr_only:     query_ob = query_ob.filter(         or_(             and_(                 department.id.in_(login_user.department_ids),  # logic 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 ok - checked.                 model.visibility == visible_dept             ),             model.visibility == visible_global,             and_(                 model.visibility == visible_company,                 model.company_id == login_user.company_id             ))     ) 

if there way can minimize code snippet in line if check or other optimization? want make below (which syntactically wrong):

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                 ))         ) 

you can create arguments or_ in list up-front, apply them or_() function:

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)) 

to database doesn't matter order options listed in or statement, if feel order matters application can use options.insert(1, model.visibility == visible_global) too.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -