比方说,我有以下型号:如何使用Django的智能选择
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)
我需要创建一个相关的下拉列表中,这样,当我选择一个大陆,我得到属于该大陆所有国家。我应该怎么做?
你看过the documentation吗?这非常简单。取决于你如何建立你的大陆/国家。我会推荐类似django-cities-light的东西,它为您提供了填充国家/地区的表格。尽管如此,我不认为它有大陆。
如果你不想做,你需要建立具有对大陆ID例如列国模型:
Continent(models.Model):
name = models.CharField()
Country(models.Model):
name = models.CharField()
continent = models.ForeignKey(Continent)
然后在位置模型设定的各场这样的:
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
)
从文档:
此示例asumes该国家模型具有大陆= ForeignKey的(洲)字段。
链接字段是同一模型上的字段,该字段也应链接。链式模型字段是链式模型的字段,对应于由链式字段链接的模型。
希望是有道理的。