【发布时间】:2019-08-20 21:37:25
【问题描述】:
我正在尝试按代理显示状态摘要。 Annotate 看起来像是要走的路,但数据结构似乎不允许我循环遍历对象并干净地填充 html 表。在传递给模板之前,我已经尝试在我的视图中进一步操作结果集,但是我已经把它弄得非常糟糕,以至于我不确定我是否正确地处理了这个问题。感谢您提供任何反馈。
我尝试使用 objects.values().annotate() 方法通过“group by”查询来查询数据库。这会输出一个字典列表。如果我可以将值作为键获取,那可能会起作用,但还有另一个列表。
直接查询用户模型可能会无意中遗漏任何没有任何 QA 事件的代理。
原始视图.py
def agent_summary(request):
lead_qas = LeadQA.objects.values('qa_agent', 'qa_status').annotate(Count('id'))
context = {'lead_qas': lead_qas}
return render(request, 'manager/agent_summary.html', context)
这给了我一个类似的数据结构:
{'qa_agent': 3, 'qa_status': 'Confirmed', 'id__count': 1}, {'qa_agent': 1, 'qa_status': 'Pending Review', 'id__count': 6}, {'qa_agent': 1, 'qa_status': 'Disqualified', 'id__count': 8}, {'qa_agent': 2, 'qa_status': 'Disqualified', 'id__count': 1}, {'qa_agent': 2, 'qa_status': 'Not Started', 'id__count': 4}, {'qa_agent': 1, 'qa_status': 'Not Started', 'id__count': 3}, {'qa_agent': 3, 'qa_status': 'Not Started', 'id__count': 4}, {'qa_agent': 1, 'qa_status': 'Confirmed', 'id__count': 4}
我无法将键完全转入我的 html 表中。
修改了views.py(更糟,也许?)
@staff_member_required
@login_required
def agent_summary(request):
lead_qas = LeadQA.objects.values('qa_agent', 'qa_status').annotate(Count('id'))
agents = User.objects.filter(is_staff=False)
qas = []
for agent in agents:
qas.append({'agent': agent.username, 'qa': list(LeadQA.objects.filter(qa_agent=agent).values('qa_status').annotate(Count('id')))})
context = {'lead_qas': lead_qas, 'agents': agents, 'qas': qas}
return render(request, 'manager/agent_summary.html', context)
这为我提供了一个数据结构,虽然乍一看似乎更好,但并没有让我更接近。
[{'agent': 'agent_1', 'qa': [{'qa_status': 'Not Started', 'id__count': 4}, {'qa_status': 'Confirmed', 'id__count': 1}]}, {'agent': 'agent_2', 'qa': [{'qa_status': 'Disqualified', 'id__count': 1}, {'qa_status': 'Not Started', 'id__count': 4}]}]
最终,我想在我的 html 模板中显示数据:
<h1>Agent Summary</h1>
<div class="container">
{% if qas %}
<table class="table">
<thead>
<th scope='col'>Agent</th>
<th scope='col'>Not Started</th>
<th scope='col'>Pending Review</th>
<th scope='col'>Disqualified</th>
<th scope='col'>Confirmed</th>
</thead>
<tbody>
{% for qa in qas %}
<tr>
<td>{{ qa.agent }}</td>
<td>{{ qa.not_started }}</td>
<td>{{ qa.pending_review }}</td>
<td>{{ qa.disqualified }}</td>
<td>{{ qa.confirmed }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
{% endif %}
没有错误,但我无法将这些结构转换为我正在寻找的表格形式。
【问题讨论】:
标签: python html django django-annotate