Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to reference the User model in Django >= 1.5

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)
like image 782
lborgav Avatar asked Sep 24 '13 22:09

lborgav


1 Answers

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.

like image 82
Ed Patrick Tan Avatar answered Sep 20 '22 18:09

Ed Patrick Tan