Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When creating a custom User model in Django what is the difference between inheriting from models.Model and AuthUser?

I've seen two ways of extending the User model in Django.

Method 1:

class User(AuthUser):
    new fields...

Method 2:

class MyUser(models.Model):
    user = models.OneToOneField(User)
    new fields...

What is the difference between them?

like image 761
bufferoverEB2A Avatar asked Oct 25 '25 19:10

bufferoverEB2A


1 Answers

The first one is multi table inheritance. (I presume you are actually speacking of django.contrib.auth.models.User here). Your new User model will have all the field that are defined in django's user model. This is managed by django implicitly creating a OneToOneField on your model.

The second, one you are creating the OneToOneField yourself. Now the django.contrib.auth.model.User model's fields do not automatically appear as parts of your own model. YOu can still access them as

 myinstance.user.parent_field

Having said all this, for option 1 you should inherit from an abstract base class rather than directly from the User model.

class MyUser(AbstractBaseUser):
   ...
like image 73
e4c5 Avatar answered Oct 27 '25 10:10

e4c5