gpt4 book ai didi

python - 在 View 中访问 django fk 相关对象作为模板

转载 作者:行者123 更新时间:2023-12-04 15:03:50 26 4
gpt4 key购买 nike

我有一个模型作为

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

# other fields...

在我的模板中,我可以很容易地以request.user.doctor的形式访问医生对象,但是在我的 View 中使用它会导致“用户”对象没有属性“医生” 错误。那么是否也可以在我的 View 中将其作为模板访问。

最佳答案

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

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

class Doctor(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
primary_key=True,
<b>related_name='doctor'</b>
)
# 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.

关于python - 在 View 中访问 django fk 相关对象作为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66504287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com