Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diffrence between get_user_model() and importing User from auth

Tags:

When I need to use the current user in a model. lets say I have a model with a current_user field, something like:

class MyModel(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,default=None)

my understanding is User can be fetched either:

1)by importing the current user:

from django.contrib.auth.models import User 

or

2) setting User to:

from django.contrib.auth import get_user_model

User = get_user_model()

I understand both will work if I am not wrong!!

So What is the main difference between those two methods if there is any? Thanks

like image 459
WISAM Avatar asked Apr 27 '18 18:04

WISAM


1 Answers

If you are using the default User model, both approaches will work.

However if you are using a custom user model (or are writing a reusable app), then you should use get_user_model() to ensure you get the correct model.

Note that the docs suggest you use settings.AUTH_USER_MODEL in foreign keys.

class MyModel(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default=None)
like image 184
Alasdair Avatar answered Oct 11 '22 17:10

Alasdair