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

如何获取Django Choice字段所有选项?搜索表单实现问题

解决商品类型Choice字段无法加载到搜索表单的问题

修正步骤及代码

1. 修正views.py中的商品类型选项获取逻辑

product_type是CharField的Choice字段,并非关联模型,因此不能用.all()方法获取选项。直接使用我们定义的TYPE常量即可:

from .choices import TYPE

def FilterView(request):
    qs = Product.objects.all()
    categories = Category.objects.all()
    ptypes = TYPE  # 替换原错误的Product.product_type.all()

    category = request.GET.get('category')
    ptype = request.GET.get('ptype')

    if is_valid_queryparam(category) and category != 'Choose...':
        qs = qs.filter(category__name=category)

    if is_valid_queryparam(ptype) and ptype != 'Choose...':
        qs = qs.filter(product_type=ptype)

    context = {
        'queryset': qs,
        'categories' : categories,
        'ptypes' : ptypes,
    }

    return render(request, 'categories/display_query.html', context)

2. 修正base.html中的下拉框循环逻辑

  • 循环变量需改为context中传入的ptypes(原代码误用了请求参数名ptype)
  • 由于TYPE是元组列表,需分别取元组的第一个元素(存储值)和第二个元素(显示文本):
<div>
    <label for="ptype">Product type</label>
    <select name="ptype">
        <option selected>Choose...</option>
        {% for type in ptypes %}
        <option value="{{ type.0 }}">{{ type.1 }}</option>
        {% endfor %}
    </select>
</div>

错误原因说明

  • views.py错误:Product.product_type.all()是针对关联模型的查询语法,不适用于CharField的Choice字段。Choice字段的选项已经在TYPE常量中定义,直接引用即可。
  • base.html错误:
    • 循环变量名写错,导致无法遍历context中的ptypes数据
    • 未正确解析Choice选项的元组结构,直接输出整个元组会导致页面渲染异常和表单提交值错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:35:15