我遇到了在给定查询上创建动态orm过滤的需求
即,给出一些输入字典:
{"orm_entitiy":"City", attribute":"id","op":">","value":"1"}
和现有的查询对象query
需要评估为:new_filtered_query = query.filter(City.id > 1)
我的问题是:
你熟悉一些解决这个问题的成熟图书馆吗?
2.我在SO和blog中看到了一个解决方案,但我很难理解这一部分:
attr = list(filter(
lambda e: hasattr(column, e % op),
['%s', '%s_', '__%s__']
))[0] % op
有人可以详细描述这背后的逻辑吗?
答案 0 :(得分:2)
让它更简洁,让这个表达变得复杂。
existing_attrs = list(filter(<filter_func>, potential_attributes))
attr = existing_attrs[0] % op
第一行生成potential_attributes
的对象列表,通过<filter_func>
的检查
第二行更简单:我们采用第一个现有属性并对其应用字符串格式。
<filter_func>
为lambda e: hasattr(column, e % op)
:如果column
具有名为e % op
的属性,则返回True,这是当前使用字符串格式的potential_attribute。
例如,如果potential_attributes
为['%s', '%s_', '__%s__']
且op
为gt
,则会检查以下属性:column.gt
,column.gt_
和column.__gt__
。
我们说我们有一个column.gt_
属性。因此,通过检查的值为%s_
,并将放在existing_attrs
列表中。然后,第二行(attr = '%s_' % 'gt'
)将生成一个字符串'gt_'
。