[Django]-Django using get_user_model vs settings.AUTH_USER_MODEL

129👍

âś…

Using settings.AUTH_USER_MODEL will delay the retrieval of the actual model class until all apps are loaded. get_user_model will attempt to retrieve the model class at the moment your app is imported the first time.

get_user_model cannot guarantee that the User model is already loaded into the app cache. It might work in your specific setup, but it is a hit-and-miss scenario. If you change some settings (e.g. the order of INSTALLED_APPS) it might very well break the import and you will have to spend additional time debugging.

settings.AUTH_USER_MODEL will pass a string as the foreign key model, and if the retrieval of the model class fails at the time this foreign key is imported, the retrieval will be delayed until all model classes are loaded into the cache.

84👍

New since Django 1.11.

Since Django 1.11 you can use get_user_model() in both cases! So if you don’t want to bother about it further, just take it.

“in both cases” means: if you need the user model for accessing its attributes, as well as if you want to define a ForeignKey/ManyToMany-relation.

From the changelog:

get_user_model() can now be called at import time, even in modules that define models.

so… is there still a reason to use settings.AUTH_USER_MODEL? Well, the docs still recommend the settings.AUTH_USER_MODEL (which is a string) for defining relations, but without giving an explicit reason. Might be beneficial for performance, but doesn’t seem to matter much.

Code example:

from django.db import models
from django.contrib.auth import get_user_model
...
    ...
    user = models.ForeignKey(
        get_user_model(),
        null=True, # explicitly set null, since it's required in django 2.x. - otherwise migrations will be incompatible later!
        ...
    )

16👍

Since Django 1.11, get_user_model() actually uses settings.AUTH_USER_MODEL:

def get_user_model():
    """
    Return the User model that is active in this project.
    """
    try:
        return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
    except ValueError:
        raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
    except LookupError:
        raise ImproperlyConfigured(
            "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
        )

13👍

settings.AUTH_USER_MODEL returns a string (the location of the User model) e.g. user_accounts.User.

get_user_model() returns the ACTUAL model class, not a string.

So in cases where you need the User model, use get_user_model(). If you need it’s location (module.model as a string), use the settings.AUTH_USER_MODEL.

1👍

as i read from book "Two Scoops of Django 3.x"
Using get_user_model():

This is bad, as it tends to create import loops.

bad example:
owner = models.OneToOneField(get_user_model()) -> BAD DONT DO IT

0👍

get_user_model() and settings.AUTH_USER_MODEL are both approaches used in Django to reference the user model when creating relationships between models. However, they serve slightly different purposes and have different use cases.

  1. get_user_model():

    get_user_model() is a function provided by django.contrib.auth that returns the user model that is currently active in the project. This function is useful when defining foreign keys or relationships to the user model within your application’s models. It ensures that you’re always referencing the correct user model, even if you change the user model in your project’s settings.

    Here’s how you would use get_user_model() in your models:

    from django.contrib.auth import get_user_model
    
    class SomeModel(models.Model):
        user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    
  2. settings.AUTH_USER_MODEL:

    settings.AUTH_USER_MODEL is a string that represents the user model. It is used in situations where you need to reference the user model outside of model definitions, such as in migrations or when creating custom user-related logic.

    For example, if you’re creating a custom user manager, you might use settings.AUTH_USER_MODEL:

    from django.conf import settings
    from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
    
    class CustomUserManager(BaseUserManager):
        def create_user(self, email, password=None, **extra_fields):
            if not email:
                raise ValueError('The Email field must be set')
            email = self.normalize_email(email)
            user = self.model(email=email, **extra_fields)
            user.set_password(password)
            user.save(using=self._db)
            return user
    
    class CustomUser(AbstractBaseUser):
        email = models.EmailField(unique=True)
        # ...
    
        objects = CustomUserManager()
    

For further Info: Django customizing auth

-12👍

A way to fallback to the default user model if AUTH_USER_MODEL is not set:

from django.conf import settings
from django.contrib.auth.models import User

USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', User)

Leave a comment