You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中根据选定模型项动态设置关联下拉框选项的问题

核心问题

你现在的写法存在两个逻辑错误:

  • 第二个下拉框直接遍历了所有小区的NumberOfUnits字段,所以会展示所有小区的单元数,而非当前选中小区的对应值
  • 你需要的是1到N的数字序列,而不是只展示NumberOfUnits这一个数值

方案1:纯前端JS实现(适合小区数据量少的场景,无需修改后端代码)

直接修改template.html即可:

<form>
    <!-- 给第一个下拉加id,value存小区id方便匹配 -->
    <select name="Complex" id="complex-select">
        {% for x in model %}
            <option value="{{ x.id }}">{{ x.ComplexName }}</option>
        {%  endfor %}
    </select> Complex

    <!-- 给第二个下拉加id -->
    <select id="unit-select"></select>
</form>

<script>
// 预先存储所有小区id对应的单元数
const unitCountMap = {
    {% for x in model %}
        {{ x.id }}: {{ x.NumberOfUnits }},
    {% endfor %}
};

const complexSelect = document.getElementById('complex-select');
const unitSelect = document.getElementById('unit-select');

// 生成单元数下拉选项的函数
function renderUnitOptions(count) {
    unitSelect.innerHTML = '';
    for(let i = 1; i <= count; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = i;
        unitSelect.appendChild(option);
    }
}

// 页面加载时默认渲染第一个小区的单元数
renderUnitOptions(unitCountMap[complexSelect.value]);

// 监听小区选择变化,重新渲染单元数
complexSelect.addEventListener('change', function() {
    const selectedId = this.value;
    renderUnitOptions(unitCountMap[selectedId]);
});
</script>

方案2:AJAX异步请求实现(适合小区数据量很大的场景)

如果小区数据非常多,把所有数据都塞到前端HTML会拖慢加载速度,可以用异步请求实现:

  1. 新增视图函数(views.py)
from django.http import JsonResponse
from .models import ComplexListClass

def get_unit_count(request):
    complex_id = request.GET.get('complex_id')
    complex_obj = ComplexListClass.objects.get(id=complex_id)
    return JsonResponse({'count': complex_obj.NumberOfUnits})
  1. 新增路由(urls.py)
path('get-unit-count/', views.get_unit_count, name='get_unit_count'),
  1. 修改template.html的JS部分
<script>
const complexSelect = document.getElementById('complex-select');
const unitSelect = document.getElementById('unit-select');

function renderUnitOptions(count) {
    unitSelect.innerHTML = '';
    for(let i = 1; i <= count; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = i;
        unitSelect.appendChild(option);
    }
}

// 页面加载默认渲染第一个小区的单元数
fetch(`/get-unit-count/?complex_id=${complexSelect.value}`)
    .then(res => res.json())
    .then(data => renderUnitOptions(data.count));

complexSelect.addEventListener('change', function() {
    fetch(`/get-unit-count/?complex_id=${this.value}`)
        .then(res => res.json())
        .then(data => renderUnitOptions(data.count));
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:18:01