Django什么是反向关系? [英] Django What is reverse relationship?
问题描述
有人可以告诉我反向关系是什么意思吗?
我已经开始使用Django,并且在文档的很多地方都提到了反向关系。到底是什么意思?为什么有用?参考这篇文章?
Can someone tell me what is reverse relationship means? I have started using Django and in lot of places in the documentation I see 'reverse relationship, being mentioned. What is it exactly mean? why is it useful? What does it got to do with related_name in reference to this post ?
推荐答案
以下是 related_name
假设您有2个模型
class Group(models.Model):
#some attributes
class Profile(models.Model):
group = models.ForeignKey(Group)
#more attributes
现在,可以从配置文件对象中执行 profile.group
。但是,如果要为配置文件对象提供 group
对象,您将如何做?那就是相关名称
或反向关系
出现的地方。
Now, from a profile object, you can do profile.group
. But if you want the profile objects given the group
object, How would you do that? Thats' where related name
or the reverse relationship
comes in.
Django,默认情况下为您提供默认的 related_name
,即ModelName(小写),后跟 set
-在这种情况下,它是 profile_set
,所以 group.profile_set
。
Django, by defaults gives you a default related_name
which is the ModelName (in lowercase) followed by _set
- In this case, It would be profile_set
, so group.profile_set
.
不过,您可以通过在 ForeignKey $中指定
related_name
来覆盖它c $ c>字段。
However, you can override it by specifying a related_name
in the ForeignKey
field.
class Profile(models.Model):
group = models.ForeignKey(Group, related_name='profiles')
#more attributes
现在,您可以访问外键了如下所示:
Now, you can access the foreign key as follows:
group.profiles.all()
这篇关于Django什么是反向关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!