I\'m running Django 1.3, using Sessions Middleware and Auth Middleware:
# settings.py
SESSION_ENGINE = django.contrib.sessions.backends.db # Persist sessions
If you return a QuerySet from your all_unexpired_sessions_for_user
function, you could limit your database hits to two:
def all_unexpired_sessions_for_user(user):
user_sessions = []
all_sessions = Session.objects.filter(expire_date__gte=datetime.datetime.now())
for session in all_sessions:
session_data = session.get_decoded()
if user.pk == session_data.get('_auth_user_id'):
user_sessions.append(session.pk)
return Session.objects.filter(pk__in=user_sessions)
def delete_all_unexpired_sessions_for_user(user, session_to_omit=None):
session_list = all_unexpired_sessions_for_user(user)
if session_to_omit is not None:
session_list.exclude(session_key=session_to_omit.session_key)
session_list.delete()
This gives you a total of two hits to the database. Once to loop over all of the Session
objects, and once to delete all of the sessions. Unfortunately, I don't know of a more direct way to filter through the sessions themselves.