Bo 7hya
Bo 7hya

Reputation: 311

Django models: Parent model accessing child model field

I have the following models

from django.contrib.auth.models import User

User = settings.AUTH_USER_MODEL    

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

class Tutor(UserProfile):
   # tutor_fields here

From User object how can I access Tutor? is it with user.profile?

user.profile.select_related('tutor') does not seem to work.

Upvotes: 1

Views: 1533

Answers (2)

Pyvonix
Pyvonix

Reputation: 827

OneToOneField work like ForeignKey except unique=True and you don't need to specify the related_name (you can specify if you want to change it).

For you example:

from django.contrib.auth.models import User

User = settings.AUTH_USER_MODEL    

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

class Tutor(UserProfile):
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='tutor')
    details = models.CharField(max_length=100)

NB: Use a ForeignKey if you want/need one Tutor for many UserProfile, else if you want one (and only one) Tutor for one UserProfile

And you can access to the Tutor bu UserProfile by UserProfile.tutor.details.

Upvotes: 1

Jenner Felton
Jenner Felton

Reputation: 807

As described in the django docs, you should be able to access it with user.user_profile.

Upvotes: 0

Related Questions