【问题标题】:How to use django-smart-select如何使用 django-smart-select
【发布时间】:2015-04-05 17:25:34
【问题描述】:

假设我有以下模型:

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

我需要创建一个从属下拉列表,以便当我选择一个大陆时,我会获得属于该大陆的所有国家/地区。我该怎么做?

【问题讨论】:

    标签: django


    【解决方案1】:

    你读过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) 字段。

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

    希望这是有道理的。

    【讨论】:

      【解决方案2】:
      1. pip install django-smart-selects
      2. 将 smart_selects 添加到您的 INSTALLED_APPS

      3. 将 smart_selects url 绑定到项目的 urls.py 中。这是 链式选择和链式多对多选择所需的。为了 示例

      4. 您的模型 Models

      5. 索引.html Index

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-18
        • 1970-01-01
        • 1970-01-01
        • 2015-02-22
        • 2020-02-09
        相关资源
        最近更新 更多