Using SQLAlchemy, determine which list values are not in a DB column
<p>Using SQLAlchemy, given a list, I'd like to determine which values in the list are not present in a given column in an sqlite DB table. One way to do it is the following:</p>

<pre><code>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))
</code></pre>

<p>Is there a faster/more efficient way to accomplish the same thing?</p>

<p>That's the most efficient I can think of (quite close to yours):</p>

<pre><code>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)
</code></pre>

python python-2.7 sqlalchemy