【发布时间】:2015-04-05 17:25:34
【问题描述】:
假设我有以下模型:
class Location(models.Model)
continent = models.CharField(max_length=20)
country = models.ForeignKey(Country)
我需要创建一个从属下拉列表,以便当我选择一个大陆时,我会获得属于该大陆的所有国家/地区。我该怎么做?
【问题讨论】:
标签: django
假设我有以下模型:
class Location(models.Model)
continent = models.CharField(max_length=20)
country = models.ForeignKey(Country)
我需要创建一个从属下拉列表,以便当我选择一个大陆时,我会获得属于该大陆的所有国家/地区。我该怎么做?
【问题讨论】:
标签: django
你读过the documentation吗?这很简单。取决于您如何设置您的大陆/国家/地区。我推荐django-cities-light 之类的东西,它为您提供填充了国家/地区的表格。我不认为它有大陆。
如果您不想这样做,您需要设置一个 Country 模型,其中包含 Continent ID 列,例如:
Continent(models.Model):
name = models.CharField()
Country(models.Model):
name = models.CharField()
continent = models.ForeignKey(Continent)
然后在 Location 模型中设置字段:
from smart_selects.db_fields import ChainedForeignKey
Location(models.Model):
newcontinent = models.ForeignKey(Continent)
newcountry = ChainedForeignKey(
Country, # the model where you're populating your countries from
chained_field="newcontinent", # the field on your own model that this field links to
chained_model_field="continent", # the field on Country that corresponds to newcontinent
show_all=False, # only shows the countries that correspond to the selected continent in newcontinent
)
来自文档:
这个例子假设 Country Model 有一个continent = ForeignKey(Continent) 字段。
链式字段是同一模型上的字段,该字段也应该被链式。 链式模型字段是链式模型的字段,对应于链式字段也链接的模型。
希望这是有道理的。
【讨论】: