Point Clear Media
Point Clear Media

Reputation: 23

Django 2.1 - linking user to related model

I am creating a Django project, and I want to create profiles of two different user types as a separate model. They will have a OneToOneField relationship with the logged-in user.

class UserMusician(models.Model):
    ...

class UserFan(models.Model):
    ...

I have seen two different ways of doing this. One, per the Django 2.1 docs shows passing in the User model, i.e.:

from django.contrib.auth.models import User

class UserMusician(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

Whereas other examples, such as the Two Scoops of Django book, suggest passing settings.AUTH_USER_MODEL, i.e.:

from django.conf import settings

class UserMusician(models.Model):
    user = models.OneToOneField(settings.AUTH.USER.MODEL)

Can anyone tell me what the differences are and what are the advantages and disadvantages to either?

I would like to for these profiles to be generated in the database when a user account is created, one or the other.

(As a 'nice to have', I'd like to allow a UserFan at a later point to become a UserMusician if they decide to switch)

Upvotes: 1

Views: 201

Answers (1)

Bernhard Vallant
Bernhard Vallant

Reputation: 50786

Tje effect is the same, no matter if you use User or settings.AUTH_USER_MODEL to specify the related model. Using settings.AUTH_USER_MODEL makes your app more "pluggable" so that it can also be used in projects that use a different user model. So if you want to reuse or release your application to the public settings.AUTH_USER_MODEL is for sure the best definition you can use.

If you want to automatically create a profile upon creation of a User instance you can use Django's post_save signal for doing that:

from django.db.models.signals import post_save
from models import UserMusician
from django.contrib.auth.models import User

def create_profile(sender, **kwargs):
    user = kwargs["instance"]
    if kwargs["created"]:
        UserMusician.objects.create(user=user)

post_save.connect(create_profile, sender=User)

Upvotes: 1

Related Questions