我有以下 Python 代码,它接受多个过滤器。然后我有一个循环对每个对象调用 .filter 。但是,当您调用多个过滤器时,这些过滤器将进行“与”运算。我怎样才能改变它,以便对过滤器的多个调用进行“或”运算。问题出在我的代码的“else”部分。
for filter_ in filters:
field_models = {'type': ProductType, 'category': ProductCategory}
if filter_['field'] in field_models:
model = field_models[filter_['field']]
organizations_products = organizations_products.join(model).filter(or_(
model.code.ilike('%{}%'.format(escape_like(filter_['value']))),
model.description.ilike('%{}%'.format(escape_like(filter_['value'])))
))
else:
field = getattr(Product, filter_['field'])
organizations_products = organizations_products.filter(
field.ilike('%{}%'.format(escape_like(filter_['value']))))
解决方案分为两部分。首先,我们必须构造 from
子句,然后构造 where
子句。
def get_joined_stmt(filters, stmt):
if 'type' in filters.keys():
stmt = stmt.join(ProductType)
if 'category' in filters.keys():
stmt = stmt.join(ProductCategory)
return stmt
def get_exprs(field, value):
def _ilike_expr(x): return '%{}%'.format(escape_like(x))
model_dict = {'type': ProductType, 'category': ProductCategory}
model = model_dict[field]
stmt = organizations_products.join(model)
try:
return [model.code.ilike(_ilike_expr(value)),
model.description.ilike(_ilike_expr(value))]
except KeyError:
return [getattr(Product, field).ilike(_ilike_expr(value))]
organizations_products = get_joined_stmt(filters, organizations_products)
where_exprs = []
for filter_ in filters.items():
where_exprs.extend(get_exprs(**filter_))
organizations_products = organizations_products.filter(or_(*where_exprs))
我是一名优秀的程序员,十分优秀!