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
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)
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