Each user in my Django application is associated with a department, and virtually every request involves some department-related processing. So I'd love to make the department object available across the entire application.
Which of these, if any, is the most appropriate approach to take:
- Custom middleware that simply retrieves the related department from the DB and attaches it to the
request
object, say asrequest.department
, sort of like Django'sAuthenticationMiddleware
makes the currently logged-in user available atrequest.user
. (See, e.g., here and here) - Placing the department in the session when the user logs in, and subsequently retrieving it in views using Django's
request.session
interface.
I haven't had an opportunity to get familiar with Django's caching features yet, but I'd like to eventually cache the department on a per-user basis to avoid the extra DB hit on every request. I see that Django's sessions provide built-in caching support. I also imagine that caching can be implemented with the first approach as well.
Is there an advantage to using sessions (#2 above) over custom middleware (#1 above) for this kind of thing? The middleware approach seems cleaner from an internal API standpoint, but I'm guessing this is exactly the kind of thing sessions are designed for -- so perhaps this is the right opportunity to start using them?
Thanks for any guidance!