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

如何让Django查询集返回符合jQuery UI Ajax自动补全要求的数据结构

你的问题出在循环内的append逻辑:当前是把poller_text、poller_id作为两个独立元素逐个加入列表,自然会得到扁平的一维数组。你只需要调整为每次循环向列表中插入一个符合目标结构的字典即可。

修改后的视图代码如下:

def autocomplete(request):
    if 'term' in request.GET:
        qs = Poller.objects.filter(poller_text__icontains=request.GET.get('term'))
        pollers = list()

        for poller in qs:
            pollers.append({
                "value": poller.poller_text,
                "label": poller.poller_text,
                "url": poller.poller_id
            })

        return JsonResponse(pollers, safe=False)

你也可以用列表推导式简化循环代码,同时可以通过only方法限制仅查询需要的两个字段,优化数据库查询性能:

def autocomplete(request):
    if 'term' in request.GET:
        term = request.GET.get('term')
        # 仅查询需要的字段,减少性能开销
        qs = Poller.objects.filter(poller_text__icontains=term).only('poller_text', 'poller_id')
        # 列表推导式直接生成目标结构列表
        pollers = [{"value": p.poller_text, "label": p.poller_text, "url": p.poller_id} for p in qs]
        return JsonResponse(pollers, safe=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:15:02