Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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?

like image 913
mazulo Avatar asked Oct 06 '15 16:10

mazulo


1 Answers

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.

like image 196
Alasdair Avatar answered Sep 20 '22 18:09

Alasdair