Reputation: 311
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
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
Reputation: 807
As described in the django docs, you should be able to access it with user.user_profile
.
Upvotes: 0