[英]Django models class relationships
在Django模型中,我有2个班级; 国家和大洲。 每个国家都使用外键链接到Continent。
class Continent(models.Model):
countries = [get countries that are linked to this continent here]
class Country(models.Model):
continent = models.ForeignKey(Continent)
如何获得“国家/地区”属性中的关联国家/地区?
在外壳中,我可以使用
Country.objects.get()
但似乎我不能在另一个类的属性中使用类名Country。
这就是related_name
的用于在Django。
创建与另一个模型的ForeignKey
关系时,可以指定该关系的反向名称。 (即,父模型可用于访问其所有子模型的名称)。 将模型定义更改为此:
class Country(models.Model):
continent = models.ForeignKey(Continent, related_name='countries')
现在从任何大陆比如说,你应该能够调用.countries
上,并得到一个queryset
有关的所有国家。 您无需向Continent
模型添加任何额外的代码。 Django会自动为您处理。
例如:
continent = Continent.Objects.get(id=1)
continent.countries.all() # returns a `queryset` of all related countries
阅读文档以获取更多有关您可以使用related_name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.