In my attempts to lower database hits, I found that on most of my
pages, auth_user is hit every time. I had an idea about caching this
object in the current session. Is this a good idea, or will it cause
more problems than it helps? If so, what type of problems will I be
My app rarely modifies the auth_user table, if at all. Here is a
quick middleware I wrote to go aloneside the current
AuthenticationMiddleware, and it works perfectly! Only 2 database
hits when viewing an account page. One hit to the session table, and
other hit to the table which holds various account settings.
def process_request(self, request):
if 'cached_user' not in request.session:
from django.contrib.auth import get_user
request.session['cached_user'] = get_user(request)
request._cached_user = request.session['cached_user']
I place this just before the standard AuthenticationMiddleware. I
will continue to run tests and see how it functions, if say the user
is added or removed from a group.
My sessions are stored in a database, which makes this interesting.
As it's only hitting the database once to grab both the session and
current user information.