gpt4 book ai didi

python - 如何在 python 中对多个过滤器调用进行 OR 运算

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:22 33 4
gpt4 key购买 nike

我有以下 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))

关于python - 如何在 python 中对多个过滤器调用进行 OR 运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982419/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com