是否可以在 SQLAlchemy 的列表中进行按成员资格过滤的查询?如果是这样,它通常会比我的替代方案更有效吗?
这就是代码当前的结构。我相信由于查询在两个 for 循环内,它可能效率低下。
def get_or_create(session, something):
object = session.query(SomeModel).filter_by(attr=something).first()
if object is None:
object = make_new_object()
return object
for things in stuff:
objects = [get_or_create(session, something) for something in things]
我想知道是否可以执行类似于以下的操作,以减少查询总数。
for things in stuff:
filter = if attr in things else None # pseudocode
objects_or_none = session.query(SomeModel).filter_by(filter).all()
objects = [make_new_object() if object is None
else object
for object in objects_or_none]
objects_or_none
看起来像这样[object, object, None, object, None, object]