Question
Asked By – Prometheus
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.
Now we will see solution for issue: Django using get_user_model vs settings.AUTH_USER_MODEL
Answer
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.
This question is answered By – knbk
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0