Under the hoods what's the difference between subclassing the user and creating a one to one field?

后端 未结 1 1545
情书的邮戳
情书的邮戳 2021-01-13 08:57

I want to implement users in my system. I know that Django already has an authentication system, and I\'ve been reading the documentation. But I don\'t know yet the differen

相关标签:
1条回答
  • 2021-01-13 09:36

    Your first example is multi-table inheritance.

    class Profile(User):
    

    If you have a profile, you can access all the fields on the user model directly (e.g. profile.username and profile.email). In this case, Django creates a OneToOneField for you automatically.

    The second example is a regular OneToOneField.

    class Profile(models.Model):
        user = models.OneToOneField(User)
    

    In this case, you cannot access profile.username and profile.email. Instead, you access these fields via the one to one field (e.g. profile.user.username and profile.user.email).

    In your case, where you are adding a profile model, I would avoid using inheritance, and use a one to one field instead. The User model has custom admins to handle passwords. If you use multi-table inheritance, then your Profile model would have to handle this as well. By using a one-to-one field, the custom admins can handle the user fields, and your Profile model admins only have to handle the additional profile fields.

    Another option is creating a custom user model. In this case you subclass an abstract class AbstractUser or AbstractBaseUser instead of the class User. If your Profile class works, then I would recommend this instead of the custom user model, because custom user models are more complicated to set up.

    0 讨论(0)
提交回复
热议问题