在django模型中,我有2个班级;国家和大陆。每个国家都与具有外键的大陆相连。
class Continent(models.Model):
countries = [get countries that are linked to this continent here]
class Country(models.Model):
continent = models.ForeignKey(Continent)
如何获取国家/地区属性中的关联国家/地区?
在shell中我可以使用
获取国家/地区Country.objects.get()
但似乎我不能在另一个类的属性中使用类名Country。
答案 0 :(得分:0)
这就是Django中related_name
的用法。
创建与其他模型的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
阅读documentation,了解有关使用related_name