[Django]-WHAT IS DIFFERENCE BETWEEN get_user_model() ,settings.AUTH_USER_MODEL and USER in django?

8đź‘Ť

They have different use cases.

You need to use get_user_model() or settings.AUTH_USER_MODEL for referencing the User model when dealing with “unknown” User model.
E.g. you are writing a module that will be used in different applications, which may use a custom User model.

If you are writing a simple app, that will no be reused, if you prefer, you can use the User model, that you can import from your model if you customized it, or from the django itself. E.g. from myapp.models import MyUserModel

In particularly, you have to use:

  • get_user_model() when you need to import the User model to query it. E.g.
User = get_user_model()
User.objects.filter(...)
  • settings.AUTH_USER_MODEL when you need to referencing User model in ForeignKey, ManyToManyField or OneToOneField. E.g.
class MyModel(models.Model):
 user = models.ForeignKey(settings.AUTH_USER_MODEL)

If you try to user get_user_model() when creating ForeignKey,ManyToManyFieldorOneToOneField` you may have circular import issues.

You also have to set settings.AUTH_USER_MODEL in your settings.py if you want to provide a custom implementation for the user model. E.g. AUTH_USER_MODEL='myapp.MyUserModel

👤Fran

1đź‘Ť

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.
Read more

settings.AUTH_USER_MODEL

If you create a custom User model then you have to add this model to your settings

User

If you don’t use custom User model, then you don’t need to add it in settings.py file. Just import the model whenever you need.

Leave a comment