谁能告诉我反向关系是什么意思?
我已经开始使用 Django,并且在文档的很多地方我看到“反向关系”被提到。它到底是什么意思?为什么它有用?它与引用的 related_name 有什么关系这个帖子 ?
这是有关的文档相关名称
假设您有 2 个模型
class Group(models.Model):
#some attributes
class Profile(models.Model):
group = models.ForeignKey(Group)
#more attributes
现在,从配置文件对象中,您可以执行以下操作profile.group
。但是如果你想要给定的配置文件对象group
对象,你会怎么做?那就是那里related name
or the reverse relationship
进来。
Django,默认情况下给你一个默认值related_name
这是模型名称(小写),后跟_set
- 在这种情况下,这将是profile_set
, so group.profile_set
.
但是,您可以通过指定一个来覆盖它related_name
in the ForeignKey
field.
class Profile(models.Model):
group = models.ForeignKey(Group, related_name='profiles')
#more attributes
现在,您可以按如下方式访问外键:
group.profiles.all()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)