本文介绍了如何使用django-smart-select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下模型:



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



我需要创建一个依赖的下拉列表当我选择一个大陆时,我得到属于该大陆的所有国家。我应该怎么做?

解决方案

你读过?这很简单取决于你的大陆/国家设置。我会推荐一些类似的内容,它为您提供了填充国家/地区。我不认为它有大陆。



如果你不想这样做,你需要设置一个国家模型,其中有一个列的Continent ID,例如:

  Continent(models.Model):
name = models.CharField()

国家(models.Model):
name = models.CharField()
continent = models.ForeignKey(Continent)

然后在位置模型中设置字段:

  from smart_selects.db_fields import ChainedForeignKey 

位置(models.Model):
newcontinent = models.ForeignKey(Continent)
newcountry = ChainedForeignKey(
Country,#你从
填充你的国家的模型chained_field = newcontinent,#这个字段链接到
chained_model_field =continent的#自己的模型的字段,#对应于newcontentent的国家/地区的字段
show_all = False,#只显示对应的国家选择ed大陆在新大陆

从文档:

希望有道理


Let's say I have the following model:

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

I need to create a dependent dropdown so that when I select a continent I get all countries belonging to that continent. How should I do it?

解决方案

Have you read the documentation? It's pretty straightforward. Depends on how you've got your continent/country set up. I'd recommend something like django-cities-light, which provides you with tables populated with countries/regions. I don't think it has continents though.

If you don't want to do that, you need to set up a Country model that has a column for Continent ID for example:

Continent(models.Model):
    name = models.CharField()

Country(models.Model):
    name = models.CharField()
    continent = models.ForeignKey(Continent)

Then in the Location model set the fields thus:

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
    )

From the docs:

Hope that makes sense.

这篇关于如何使用django-smart-select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 15:26