根据值字典编写一个空单元格的表

2024-09-26 18:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我的应用程序中有此视图:

def context_detail(request, context_id):
c = get_object_or_404(Context, pk=context_id)
scs = SherdCount.objects.filter(assemblage__context=c).exclude(count__isnull=True)
total = sum(sc.count for sc in scs)
table = []
forms = []
for a in c.assemblage_set.all():
    for sc in a.sherdcount_set.all():
        forms.append(sc.typename)
forms_set = set(forms)
for a in c.assemblage_set.all():
    diko = {}
    diko['assemblage'] = a
    for f in forms_set:
        for sc in a.sherdcount_set.all():
            if f == sc.typename:
                diko[f] = sc.count
            else:
                diko[f] = 0
    table.append(diko)
return render_to_response('tesi/context_detail.html',
    {'context': c, 'total': total, 'sherdcounts': scs, 'table': table, 'forms': forms_set},
    context_instance=RequestContext(request))

两个for循环的目的是创建一个字典列表,其中包含SherdCount.count参考SherdCount.typename外键(我能够做到,即使当前代码有点混乱)。在

“表”列表应包含如下内容:

^{pr2}$

但许多0值显然是错误的。即使可能有一些零(我指的是空单元格)

问题是,一旦我构建了这样一个列表,如何在模板中创建一个包含所有单元格的表(例如,每种类型一行,每上下文一列,在单元格处有SherdCount)?在

斯特科


Tags: inforcountcontexttableformsalltotal
1条回答
网友
1楼 · 发布于 2024-09-26 18:16:56

这是数据结构。在

[{<Type1>: 16,
  <Type2>: 10,
  <Type3>: 12,
  <Type4>: 7,
  <Type5>: 0,
  'assemblage': <Assemblage1>},
 {<Type1>: 85,
  <Type2>: 18,
  <Type3>: 21,
  <Type4>: 12,
  <Type5>: 2,
  'assemblage': <Assemblage2>},
 ...]

问题是生成的表必须按行顺序生成,而这个字典列表是按列顺序生成的。因此,dict列表必须按行主顺序旋转。在

^{pr2}$

此外,它有助于将结果形式化为列表列表;字典没有固有的顺序。在

^{3}$

下面是将titlesfinal呈现为表的模板。在

<table>
  <tr>
    {% for t in titles %}<th>{{t}}</th>{% endfor %}
  </tr>
  {% for row in final %}
  <tr>
      {% for cell in row %}<td>{{cell}}</td>{% endfor %}
  </tr>
  {% endfor %}
</table>

相关问题 更多 >

    热门问题