You need to enable JavaScript to run this app. Django如何实现仅展示存在成员的国家-州-城市级联筛选下拉
优惠活动
大模型
产品
解决方案
定价
更多

Django如何实现仅展示存在成员的国家-州-城市级联筛选下拉

项目配置与问题说明

基础配置

  • 项目拆分了csc、members两个应用
  • csc应用包含国家、州、城市三级地域模型,对应数据库存储了全量的国家、州、城市基础数据
  • members应用实现了自定义用户模型,用户模型通过外键关联csc应用的国家、州、城市模型
  • 目前已在Django后台管理系统中,通过django-smart-selects实现了地域字段的三级级联关联效果,前端用户列表也已通过django-filter实现基础的地域维度筛选能力

核心需求

前端的国家、州、城市三个筛选下拉框,仅展示存在关联注册成员的地域选项,不再加载csc库中的全量地域数据,同时需要保障三个下拉框之间原有的级联联动效果。

现有代码参考

csc应用 models.py

class Country(models.Model):
    name = models.CharField(_('Country'), max_length=255, null=True)
    country_code = models.CharField(_('Code'), max_length=10, null=True)
    iso_code_short = models.CharField(_('ISO Code Short'), max_length=2, null=True)
    iso_code_long = models.CharField(_('ISO Code Long'), max_length=3, null=True)

    def __str__(self):
        return self.name


class State(models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(_('State'), max_length=255, null=True)

    def __str__(self):
        return str(self.name)


class City(models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    state = ChainedForeignKey('State', chained_field="country", chained_model_field="country", show_all=False, auto_choose=True)
    name = models.CharField(_('City'), max_length=255, null=True)

    def __str__(self):
        return str(self.name)

members应用 models.py

class CustomUser(AbstractUser):
    username = None
    email = models.EmailField(_('Email'), max_length=255, unique=True)
    first_name = models.CharField(_('First Name'), max_length=100, null=True, blank=True)
    last_name = models.CharField(_('Last Name'), max_length=100, null=True, blank=True)
    country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True)
    state = ChainedForeignKey(State, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, null=True, blank=True)
    city = ChainedForeignKey(City, chained_field="state", chained_model_field="state", show_all=False, auto_choose=True, null=True, blank=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

筛选逻辑代码(filter.py)

class UserFilter(django_filters.FilterSet):
    country = CharFilter(label=_('Country'), field_name='country__name', lookup_expr='icontains')
    state = CharFilter(label=_('State'), field_name='state__name', lookup_expr='icontains')
    city = CharFilter(label=_('City'), field_name='city__name', lookup_expr='icontains')

    class Meta:
        model = User
        fields = ['country', 'state', 'city']

内容的提问来源于stack exchange,提问作者Sukumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 15:06:04