假设我有2个模型:A和B
A是主表,B是其子表(一对多关系)
A中的某些内容在B中具有多个子类别 有些在B中没有项目
所以,我想在HTML中的select标记中显示此内容,目的是当我从A中选择一个选项时,我希望另一个选择选项显示存储在B中的A的子内容
我所知道的是
contents=A.objects.all()
和html页面
{for content in contents}
<option value={{content.id}}>{{content}}</option>
{endfor}
但是我不知道如何在另一个选项中显示B的子内容,该选项会根据第一个选项更改子内容。
答案 0 :(得分:0)
根据我的理解,您想根据第一选择中的选定选项动态过滤第二选择的选项。有一个名为 django-smart-selects 的不错的库,它使用 ChainedForeignKey 关系。因此,例如,如果您有两个名为国家/地区和城市的模型,并且想要在城市中选择基于所选的国家/地区,您只需执行以下操作即可:
from smart_selects.db_fields import ChainedForeignKey
class Country(models.Model):
.......
class City(models.Model):
country = models.ForeignKey(Country)
.......
class Location(models.Model):
country = models.ForeignKey(Country)
city = ChainedForeignKey(
City,
chained_field="country",
chained_model_field="country",
show_all=False,
auto_choose=True,
sort=True)
.......
您可以通过键入pip
与pip install django-smart-selects
安装智能选择。