Django: how to define a one-to-one relationship to a table in admin?

563 views Asked by At

Good day, friends!

I am trying to define a one-to-one relationship to an user in django admin. Below is my code in models.py in an app:

from django.db import models

class Tutor(models.Model):
    account = models.OneToOneField([A User from Admin]) # what should I code here?
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)

What should I write instead of [A User from Admin]?

Thanks.

2

There are 2 answers

2
Iqbal Hussain On BEST ANSWER
from django.db import models
from django.contrib.auth.models import User
#You need to add the aforementioned line if you want to load User model here

class Tutor(models.Model):
    account = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)

Now if you want to access it by user info then you can. Say, you need to access a user's first_name. Then you will just run the relationship query here:

user_info = User.objects.get(username='someone')
first_name = user_info.tutor.first_name

Additional information: If you need to add first_name and last_name for User you do not need to add another table. Just extends the UserCreationForm and add additional field for User Model.

1
LonnyT On

The user model belongs to django.contrib.auth

from django.contrib.auth.models import User
from django.db import models

class Tutor(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)

Edit

Like stated in the comments its better to reference the model via the AUTH_USER_MODEL setting. This way the code doesn't break if you change the user model. Django Docs - Referencing the User model

from django.conf import settings
from django.db import models

class Tutor(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)