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

Django无需向URL传递ID显示数据库内容及双表同步遍历问题咨询

问题原因

  1. 视图层的循环逻辑错误:你在for循环中反复覆盖hello变量,循环结束后hello仅保留最后一次查询的GoCustomerStatus对象,传到模板后所有行自然只会显示同一条最后一条数据。
  2. 你的GoCustomerRegistration和GoCustomerStatus本身就是一对一关联关系,完全不需要单独查询状态表,直接用Django ORM自带的关联查询即可拿到每个用户对应的状态数据。

修复步骤

1. 修改views.py

删除冗余的循环查询逻辑,改用select_related预加载关联数据,避免N+1查询问题:

@login_required
def preview(request):
    # select_related会提前关联查询GoCustomerStatus表,只需1次数据库请求
    detail = GoCustomerRegistration.objects.select_related('gocustomerstatus').all()
    next_event = Event.objects.last()
    context = {
        'detail': detail,
        'event': next_event,
    }
    return render(request, 'customers_preview.html', context)

2. 修改模板文件

将原来的hello.value替换为对应每个用户的关联状态值,同时修正你模板里写错的h.value字段:

{% for item in detail %}
<tr>
  <td>
    <a class="text-black text-decoration-none" href="{{ item.photo.url }}">
      <img class="rounded-circle me-2" style="object-fit: contain; background-color:#91debb; border:1px solid palegreen;" alt="" width="30" height="30" src="{{ item.photo.url }}"></a>
  </td>
  <td>
    <a class="text-black lg:hover:text-blue-400 text-decoration-none" href="{% url 'customer_detail' pk=item.id %}">{{ item.name }}</a>
  </td>
  <td class="text-capitalize">{{ item.type }}</td>
  <td>{{ item.destination }}</td>
  <td>{{ item.age }}</td>
  <td>{{ item.time_of_submission }}</td>
  <td>
    <span>{{ item.gocustomerstatus.value }}%</span>
    <div class="col">
      <div class="progress progress-sm">
        <div class="progress-bar progress-bar-striped bg-success" aria-valuenow="{{ item.gocustomerstatus.value }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ item.gocustomerstatus.value }}%;"><span class="visually-hidden"></span>
        </div>
      </div>
    </div>
  </td>
{% endfor %}

补充说明

如果存在部分GoCustomerRegistration没有对应的GoCustomerStatus记录的情况,直接访问item.gocustomerstatus会报错,可以用模板过滤器处理异常,比如写成{{ item.gocustomerstatus.value|default:0 }},没有对应状态时会默认显示0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:39:02