[Fixed]-Best way to reference the User model in Django >= 1.5


UPDATE: As of Django 1.11, get_user_model can now be called at import time, even in modules that define models.

That means you could do this:
models.ForeignKey(get_user_model(), ...)

Original answer (Django <= 1.11)

You might experience circular reference issues if you use get_user_model at module level. Another option for importing the auth user model is:

from django.conf import settings

AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

# models
class Article(models.Model):
    author = models.ForeignKey(AUTH_USER_MODEL)

The getattr will return Django’s default user model, which is auth.User, if AUTH_USER_MODEL is not detected in the settings file.


As long as you just extend the user model (or don’t touch it at all), you an do:

from django.contrib.auth.models import User

author = models.ForeignKey(User)  


I don’t think “Readability counts” is about second case.

author = models.ForeignKey(User)

looks like

from django.contrib.auth.models import User

... # Imagine tons of code here    

class Article(models.Model):
    author = models.ForeignKey(User)

for me. Will be surprised when won’t work

article.author.get_full_name() # or any auth.models.User specific method
👤I S


In my opinion the second one. With the second way, you can have everything in the same file and you don’t need to modify 2 different files, with the possible problems you can find with that.

Leave a comment