Home > OS >  Rewriting User standard model when customizing User class
Rewriting User standard model when customizing User class

Time:06-24

guys! I'm using standard User model from django.contrib.auth.models import User.

And I want to customize User model, expecially to add a field with ForeignKey. For example:

class User(models.Model):
    this_users_team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) 

If I wrote this code is the django will overwriting standard User model with my data in databases or will it cause the issues? One more time, I haven't not any class User in my code. But I'm using User in other models, for example:

id_user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)

CodePudding user response:

It's not recommended to customise the provided User model.

If you don't want a Custom User model (eg subclass from AbstractUser - which is a copy of the default user model designed to allow extension), then the simplest way to extend user is to create another model with a one to one relationship to it.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
    team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) 

With the related name you can refer to user.profile.team

Plenty more on this subject in the docs

  • Related