具有相同字段的 Django 用户模型

Django User model with same fields

我看到了有关如何通过为 Django 用户模型提供一对一关系来扩展 Django 模型的教程。 我的问题是,如果我们在用户和个人资料(从用户扩展)模型上有相同的字段,即电子邮件和用户名。 当用户使用用户模型在我们的网站上注册时,个人资料模型是否会从用户模型继承相同的用户名和电子邮件?

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)

When the user register on our site using User the model, does the Profile model will inherit the same username and email from User model?

,您不继承用户模型,您只是创建一个引用用户的新模型,它发生 有一些相同的字段。从软件设计 point-of-view 来看,这也很糟糕。想象一下,您后来向用户模型添加了一个字段,并且不知何故它与 Profile 相同,然后突然间数据应该不同了?

不需要在Profile中额外存储数据。如果你有一个像 my_profile 这样的 Profile 对象,你可以访问存储在相关用户中的电子邮件地址:

<em>my_profile</em><strong>.user.email</strong>

您还可以制作将从用户那里获取的属性,例如:

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 <strong>name</strong>(self):
        if self.user_id is not None:
            return self.user.username
    
    @property
    def <strong>email</strong>(self):
        if self.user_id is not None:
            return self.user.email

存储相同的数据是数据重复的一种形式,通常会使软件更难维护:这意味着对于 User 模型的每次更新,或Profile 模型,您将需要与其他模型同步。这很容易出错,导致 Profile 的电子邮件地址可能与相关 User 的电子邮件地址不同,反之亦然,这会导致很多问题,比如将电子邮件发送到错误的电子邮件地址等


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 the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.