gpt4 book ai didi

python - 我可以使用 OneToOneField 的反向关系吗

转载 作者:行者123 更新时间:2023-12-01 01:47:23 25 4
gpt4 key购买 nike

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'

最佳答案

由于您使用 OneToOneField ,这意味着目标模型(此处 User )最多一个 EmailActivation附加到它的对象。

因此,反向关系不是 somemodel_set ,但只是somemodel .

所以你应该写:

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

这将直接获取与User相关的对象。实例obj .

Note: It is possible that no EmailActivation 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 EmailActiva<b>t</b>ion (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.

关于python - 我可以使用 OneToOneField 的反向关系吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51124895/

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