Django OneToOneField关系访问

时间:2015-05-07 12:41:46

标签: django one-to-one

嘿,我现在有点迷失方向。我有一个简单的问题。

嗯,我得到了这个模型。

class UserProfile(models.Model)

   user = models.OneToOneField(User, related_name='profile')
   bool = models.BooleanField(default=False)

然后我想访问这个" bool"来自我的admin.py的字段,有一点我想测试bool是真还是假。

def some_method(request)

如果它在标准用户模型中有些bool我会像

那样进行测试
if request.user.standard_bool:

但是我如何才能访问models.py中定义的bool? 我以为那会是

if request.user.profile.bool:

但它给了我"用户没有个人资料。"

P.S。 我最终发现这不是我问题的根源。 在我尝试了建议的解决方案后,它仍然无法工作......直到我 更改了UserProfile类的save和create_user_profile以保存配置文件。不过,我会将此标记为已解决。

2 个答案:

答案 0 :(得分:0)

错误信息非常清楚。您没有为已登录用户设置UserProfile实例。

您可以使用以下代码解决此类情况:

profile = UserProfile.objects.filter(user=request.user).first()
if profile and profile.bool:
    ...

答案 1 :(得分:-1)

find / -type f -print0 | xargs -0 -I name bash -c 'fnchash "name"' fnchash () { echo "$1" } request.user

相关联
django-auth User Model

记住user = get_object_or_404(User, username=request.user.username) if user.profile.bool: 中的profile来自您的UserProfile模型下的user.profile.bool