我能用OneToOneField的反向关系吗

2024-10-04 05:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

class EmailActivaion(models.Model):
user =     models.OneToOneField(User,on_delete=models.CASCADE)

我能做以下代码吗:

qs=User.objects.filter(email='bla@bla.com')
obj=qs.first()
em = obj.EmailActivaion_set.all()

因为我得到了以下错误:

AttributeError: 'User' object has no attribute 'EmailActivaion_set'

Tags: 代码objmodelonmodelsdeleteclasscascade
1条回答
网友
1楼 · 发布于 2024-10-04 05:28:27

由于您使用OneToOneField,这意味着目标模型(这里User)最多有一个对象附加到它。你知道吗

因此,反向关系不是somemodel_set,而是简单的somemodel。你知道吗

所以你应该写:

# fetches the single EmailActivation instance,
# or raises an EmailActivation.DoesNotExist error (in case no exists)
em = obj.emailactivation

这将直接获取与User实例obj相关的对象。你知道吗

Note: It is possible that noEmailActivation instance is associated with this User, in that case it will raise a EmailActivation.DoesNotExist error, so perhaps you want to write try-except logic around this.

你知道吗

Note I fixed a spelling error: it is EmailActivation (with two ts)

你知道吗

Note: the name of the relation is the name of the model in lowercase, so not obj.EmailActivation, but obj.emailactivation.

你知道吗

Note: typically it is better to refer to the settings.AUTH_USER_MODEL instead of to the User model directly: if you later change the user model to a custom model, then you do not have to rewrite all those models. By default settings.AUTH_USER_MODEL is User, but you can later set it to a different model.

相关问题 更多 >