是否可以通过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]