有人能告诉我什么是反向关系意味着什么?我已经开始使用Django了,在文档的很多地方,我看到'反向关系,被提及.这是什么意思?为什么有用?在引用这篇文章时,它与related_name有什么关系?
kar*_*ikr 39
这是related_name的文档
假设您有2个型号
class Group(models.Model):
#some attributes
class Profile(models.Model):
group = models.ForeignKey(Group)
#more attributes
Run Code Online (Sandbox Code Playgroud)
现在,您可以从配置文件对象中执行此操作profile.group.但是如果你想要给出group对象的配置文件对象,你会怎么做?多数民众赞成在哪里related name或reverse relationship进来.
默认情况下related_name,Django为您提供一个默认值,即ModelName(小写)后跟_set- 在这种情况下,它将是profile_set,所以group.profile_set.
但是,您可以通过related_name在ForeignKey字段中指定a来覆盖它.
class Profile(models.Model):
group = models.ForeignKey(Group, related_name='profiles')
#more attributes
Run Code Online (Sandbox Code Playgroud)
现在,您可以按如下方式访问外键:
group.profiles.all()
Run Code Online (Sandbox Code Playgroud)
小智 5
为了更清楚地了解情况,您可以假设当我们使用反向关系时,它会在引用模型中添加一个额外的字段:
例如:
class Employee(models.Model):
name = models.CharField()
email = models.EmailField()
class Salary(models.Model):
amount = models.IntegerField()
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='salary')
Run Code Online (Sandbox Code Playgroud)
在 Salary 模型中使用 related_name 之后,现在您可以假设 Employee 模型将多一个字段:salary。
例如,可用字段现在为:
name,email, 和salary
要查找员工,我们可以简单地这样查询:
e = Employee.objects.filter(some filter).first()
要检查他们的工资,我们可以通过编写来检查
e.salary(现在我们可以使用工资作为员工模型中的属性或字段)。这将为您提供该员工的工资实例,您可以通过写入找到金额e.salary.amount。这将为您提供该员工的工资。
在多对多关系的情况下,我们可以使用.all()然后迭代它。