检查Django中OneToOneField是否为None [英] Check if OneToOneField is None in Django

查看:119
本文介绍了检查Django中OneToOneField是否为None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个这样的模型:

class Type1Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    ...


class Type2Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    ...

如果用户具有Type1或Type2配置文件,我需要执行某些操作:

I need to do something if the user has Type1 or Type2 profile:

if request.user.type1profile != None:
    # do something
elif request.user.type2profile != None:
    # do something else
else:
    # do something else

但是,对于没有type1或type2配置文件的用户,执行这样的代码会产生以下错误:

But, for users that don't have either type1 or type2 profiles, executing code like that produces the following error:

Type1Profile matching query does not exist.

如何查看用户的个人资料类型?

How can I check the type of profile a user has?

谢谢

推荐答案

要检查(OneToOne)关系是否存在,可以使用 hasattr function:

To check if the (OneToOne) relation exists or not, you can use the hasattr function:

if hasattr(request.user, 'type1profile'):
    # do something
elif hasattr(request.user, 'type2profile'):
    # do something else
else:
    # do something else

这篇关于检查Django中OneToOneField是否为None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆