使用SQLAlchemy,给定一个列表,我想确定列表中的哪些值不存在于sqlite DB表的给定列中。一种方法是:
def get_user_ids_not_in_DB(self, user_ids):
query__belongs = User_DB.user_id.in_(user_ids)
select__user_ids_in_DB = self.SQL_Helper.db.query(User_DB.user_id).filter(query__belongs)
user_ids_in_DB = zip(*select__user_ids_in_DB.all())[0]
return list(set(user_ids) - set(user_ids_in_DB))
是否有更快/更有效的方法来完成同样的事情?
答案 0 :(得分:2)
选择所有用户然后将其连接到别名为User_db对象然后为非别名user_id添加过滤器为空。
# an alias to a subquery on a table. All user ids in you list
ualias = aliased(User_DB, User_DB.user_id.in_(user_ids))
results = self.SQL_Helper.db.query(User_DB.user_id)\
.outerjoin(ualias, ualias.user_id == User_DB.user_id)\
.filter(ualias.user_id == None)
赦免错别字,但这就是它的要点。
答案 1 :(得分:1)
这是我能想到的最有效率(非常接近你的):
from future_builtins import zip, map
from operator import itemgetter
def get_user_ids_not_in_DB(self, user_ids):
unique_ids = set(user_ids)
query__belongs = User_DB.user_id.in_(unique_ids)
select__user_ids_in_DB = self.SQL_Helper.db.query(User_DB.user_id).filter(query__belongs)
user_ids_in_DB = set(map(itemgetter(0), select__user_ids_in_DB))
return (unique_ids - user_ids_in_DB)