简体   繁体   中英

access django fk related objects in view as template

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.

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,
        
    )
    # 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM