Under the hoods, what's the difference between subclassing a user and creating a single field?

I want to implement users in my system. I know that Django already has an authentication system, and I am reading the documentation. But I don’t know 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 do not want to know why to use this or that, but what happens under the hoods. Who cares?

+5
source share
1 answer

Your first example is the inheritance of multiple tables .

 class Profile(User): 

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

The second example is the usual 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 through a single field (for example, profile.user.username and profile.user.email ).

In your case, when you add a profile model, I would avoid using inheritance and use a single field instead. The User model has user admins for handling passwords. If you use multiple table inheritance, then your profile model would also have to handle this. Using a one-to-one field, user admins can process user fields, and profile model administrators must process additional profile fields.

Another option is to create a custom model. In this case, you subclass the AbstractUser or AbstractBaseUser abstract class instead of the User class. If your profile class works, then I would recommend it instead of a user model, because user user models are harder to configure.

+9
source

Source: https://habr.com/ru/post/1233073/


All Articles