Django using get_user_model vs settings.AUTH_USER_MODEL

django, python

Solution

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.

Problem

Reading the Django Documentation: get_user_model() Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active User model – the custom User model if one is specified, or User otherwise. When you define a foreign key or many-to-many relations to the User model, you should specify the custom model using the AUTH_USER_MODEL setting. I'm confused with the above text. Should I be doing this: ``` author = models.ForeignKey(settings.AUTH_USER_MODEL) ``` or this... ``` author = models.ForeignKey(get_user_model()) ``` Both seem to work.

Original source