python - 检查 Django 中的 OneToOneField 是否为 None

标签 python django django-models one-to-one

我有两个这样的模型:

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


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

如果用户有 Type1 或 Type2 配置文件,我需要做一些事情:

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

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

Type1Profile matching query does not exist.

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

谢谢

最佳答案

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

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

关于python - 检查 Django 中的 OneToOneField 是否为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3463240/

相关文章:

python - 如何执行 makefile 来重新编译 django oscar 资源?

Django:使用整数设置外键?

django - 筛选 PointField 的查询集字段以查找特定距离范围内的项目不正确

mysql - 带FOREIGN KEY的Django Mysql迁移报错150

python - 在 Django 中使用二进制图像数据构建 multipart/form-data 给了我一个 UnicodeDecodeError

django - 创建 CustomUser 时 Syncdb 错误

python - 如何按行拆分 pandas 数据框并包含创建的每个新数据框的标题?

python - 在大多数 IDE 中自动补全不适用于 PyQT4 和 PyKDE4

python - python中如何通过调用__init__方法中的方法来引入对象的属性?

python - 有没有办法在 django 模板中使用 'and' 来检查 2 个变量?