I saw tutorial on how to extend django model by giving 1-to-1 relationship to the django user model. My question is, if we have same fields on both User and profile(extend from user) model i.e email and username. When the user register on our site using User model, does the profile model will inherit the same username and email from User model?
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, blank=True, null=True)
email = models.EmailField(max_length=500, blank=True, null=True)
location = models.CharField(max_length=200, blank=True, null=True)
CodePudding user response:
When the user register on our site using
User
the model, does theProfile
model will inherit the same username and email fromUser
model?
No, you do not inherit from the user model, you simply create a new model that refers to a user, and it happens to have some fields that are the same. It would also be bad from a software design point-of-view. Imagine that you later add a field to your user model and somehow it is the same as the Profile
, then all of a sudden the data should be different?
There is no need to store the data an extra time in the Profile
. If you have a Profile
object like my_profile
, you can access the email address stored in the related user with:
my_profile.user.email
You can also make properties that will obtain it from the user, like:
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True,
blank=True
)
location = models.CharField(max_length=200, blank=True, null=True)
@property
def name(self):
if self.user_id is not None:
return self.user.username
@property
def email(self):
if self.user_id is not None:
return self.user.email
Storing the same data is a form of data duplication and often makes software harder to maintain: it means that for every update of the User
model, or the Profile
model, you will need to synchronize with the other model. This can easily go wrong, resulting in the fact that the Profile
can have a different email address than the related User
and vice versa, resulting in a lot of problems where one sends emails to the wrong email address, etc.
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.