5

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 difference between

from django.contrib.auth.models import User 
class Profile(User):
    # others fields

And

from django.contrib.auth.models import User 
class Profile(models.Model):
    user = models.OneToOneField(User)
    # others fields 

I don't want to know why to use one or another, but what happens under the hoods. What's the difference?

Alasdair
  • 298,606
  • 55
  • 578
  • 516
mazulo
  • 648
  • 5
  • 11
  • I'll say this is a duplicate of [Django: Why create a OneToOne to UserProfile instead of subclassing auth.User?](http://stackoverflow.com/questions/5452288/django-why-create-a-onetoone-to-userprofile-instead-of-subclassing-auth-user) because the top answer there talks about the "under the hood" stuff. Also see https://stackoverflow.com/questions/3221745/django-when-extending-user-better-to-use-onetoonefielduser-or-foreignkeyuse – Nick T Oct 06 '15 at 17:55
  • I don't want to know why but what happens under the hoods, and @Alasdair answered it. – mazulo Oct 06 '15 at 18:17

1 Answers1

10

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • I finally understood the difference! I didn't know that Django creates a `OneToOneField` when you inherits from User. I don't know what means multi-table inheritance, but I'll read the link about. Thanks! – mazulo Oct 06 '15 at 18:13