【问题标题】:access django fk related objects in view as template在视图中访问 django fk 相关对象作为模板
【发布时间】:2021-03-06 09:37:44
【问题描述】:

我有一个模特

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

    # other fields... 

在我的template 中,我可以轻松地以request.user.doctor 访问医生对象,但在我的views 中使用它会导致'User' object has no attribute 'doctor' 错误。那么是否可以在我的 views 中以 templates 的形式访问它。

【问题讨论】:

    标签: python django django-views django-templates


    【解决方案1】:

    related_name=… parameter [Django-doc]reverse 中关系的名称,因此要从 User 访问 Doctor 对象,因为您已将其设置为 user,因此您可以访问Doctor 对象与 request.user.user,但这是误导。

    因此,您最好将关系重命名为:

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

    注意:通常使用settings.AUTH_USER_MODEL [Django-doc] 引用用户模型比直接使用User model [Django-doc] 更好。更多信息可以查看referencing the User model section of the documentation

    【讨论】:

    • 天哪!非常感谢您,先生:) 是的,就是这样。
    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2021-09-07
    • 2022-07-17
    • 2016-04-19
    • 2012-12-28
    • 2018-07-01
    • 1970-01-01
    相关资源
    最近更新 更多