Django 什么是反向关系? [英] Django What is reverse relationship?

查看:27
本文介绍了Django 什么是反向关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我反向关系是什么意思?我已经开始使用 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 对象的配置文件对象,您会怎么做?这就是 related name反向关系 进来的地方.

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 来覆盖它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆