What is the best way to reference User model in Django >= 1.5?
After reading Referencing the User model, I've started using (1) for a while:
(1)
from django.conf import settings
from django.db import models
class Article(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL)
But following the Zen of Python, Readability counts, why not this:
(2)
from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
class Article(models.Model):
author = models.ForeignKey(User)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With