Python模型Foreignkey向后关系

时间:2015-12-06 13:22:17

标签: python django

我需要通过大陆模型的属性“国家”来保存一个大陆的所有国家。我怎样才能做到这一点? 感谢。

from django.db import models

class Continent(models.Model):
    name = models.CharField(max_length=255, unique = True)
    code = models.CharField(max_length=255, unique = True)
    allCountries = models.Manager()
    countries = ???

class Country(models.Model):
    name = models.CharField(max_length=255 )
    capital = models.CharField(max_length=255 )
    code = models.CharField(max_length=255, unique = True)
    population = models.PositiveIntegerField()
    area = models.PositiveIntegerField()
    continent = models.ForeignKey(Continent)

1 个答案:

答案 0 :(得分:2)

要从特定大陆获取所有国家/地区,您必须执行以下操作:

continent = Continent.objects.get(name='Europe')
countries = continent.country_set.all() # returns all countries from Europe

您无需在Continent

中添加国家/地区字段