比方說,我有以下型號:如何使用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的(洲)字段。
鏈接字段是同一模型上的字段,該字段也應鏈接。鏈式模型字段是鏈式模型的字段,對應於由鏈式字段鏈接的模型。
希望是有道理的。