access django fk related objects in view as template

Viewed 68

I have a models as

class Doctor(models.Model):
    user = models.OneToOneField(
           User,
           on_delete=models.CASCADE,
           primary_key=True,
           related_name="user")

    # other fields... 

In my template, I easily can access the doctor object as request.user.doctor but using it in my views it causes the 'User' object has no attribute 'doctor' Error. so is it possible to access it as templates in my views too.

1 Answers

The related_name=… parameter [Django-doc] is the name of the relation in reverse, so to access the Doctor object from a User, since you have set this to user, you thus access the Doctor object with request.user.user, but that is misleading.

You thus better rename the relation to:

class Doctor(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        primary_key=True,
        related_name='doctor'
    )
    # other fields …

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Related