如何使用django-smart-select

时间:2015-04-05 17:25:35

标签: django

我们说我有以下型号:

class Location(models.Model) continent = models.CharField(max_length=20) country = models.ForeignKey(Country)

我需要创建一个依赖的下拉列表,这样当我选择一个大陆时,我会得到属于该大陆的所有国家/地区。我该怎么办?

2 个答案:

答案 0 :(得分:6)

您是否阅读过the documentation?这很简单。取决于你如何建立你的大陆/国家。我建议使用类似django-cities-light的内容,它会为您提供填充国家/地区的表格。我不认为它有大陆。

如果您不想这样做,则需要设置具有大陆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)字段。

     

链式字段是同一模型上的字段,字段也应该链接。   链式模型字段是链式模型的字段,对应于链式字段链接的模型。

希望这是有道理的。

答案 1 :(得分:5)

  1. pip install django-smart-choices
  2. 将smart_selects添加到您的INSTALLED_APPS

  3. 将smart_selects网址绑定到您的项目的urls.py中。这是 链接选择和链接ManyToMany选择所需的。对于 示例

  4. 你的模特 Models

  5. 的index.html Index