Search code examples
pythondjangodjango-modelsdjango-contribdjango-cache-machine

How to get Django Cache Machine to work on django.contrib.auth.models.User?


I'm using Django Cache Machine to cache my Django ORM objects. It's a great piece of software. It has immensely reduced the database accesses for nearly all my models -- and it is simple to use.

However, one model is still not being cached: django.contrib.auth.models.User. Because that is not my own application code, I didn't outfit it with the CachingMixin that Cache Machine instructions tell you to add to each of your models. So now even though all my own applications' models are being cached, the User model is not. And so there are still numerous unneccesary database accesses.

What is the best way to eliminate these database accesses? django.contrib.auth.models.User is not part of my code-base in Git. I would prefer not altering the source code of that class or module at all.


Solution

  • You need to make a custom user model which preserves the functionality of the Dajgno User model while adding the caching mixin.

    I'm guessing this would be enough:

    from caching.base import CachingManager, CachingMixin
    from django.contrib.auth.models import AbstractUser, UserManager
    
    class CachedUserManager(CachingManager, UserManager):
        pass
    
    class CachedUser(CachingMixin, AbstractUser):
        objects = CachedUserManager()
    

    and of course, in your settings.py:

    AUTH_USER_MODEL = 'myapp.CachedUser'