我有一些大的数据集,我循环显示数据表。麻烦在于循环需要花费大量的时间,这是正确的,因为这是一个内部工具,但我想改进它。更好的方式来循环浏览Django模板中的多个列表
型号:
class Metric_Data(models.Model):
metric = models.ForeignKey(Metric)
count = models.IntegerField()
start_date = models.DateField()
我显示表,其中的第一列是日期,那么每个以下列列出该日期的计数的度量。像这样:
Dates Metric Metric Metric ...
10/11 10 11 12
11/11 22 100 1000
... ... ... ...
我试图循环遍历视图中的数据,并创建表得到的名单,并通过这种对模板进行渲染,但有几个指标上千个数据点每公吨,这是相当缓慢的。因为我已经切换到模板标签:
def getIndex(parser, token):
try:
tag_name, a_list, index = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0]
return GetIndexNode(a_list, index)
class GetIndexNode(template.Node):
def __init__(self, a_list, index):
self.the_list = template.Variable(a_list)
self.index = template.Variable(index)
def render(self, context):
try:
the_list = self.the_list.resolve(context)
i = self.index.resolve(context)
return the_list[i]
except template.VariableDoesNotExist:
return ''
这仍然是相当缓慢的,这只是可能,因为这是我第一次写一个模板标签,我做错了什么。
编辑:
def show_all(request):
metrics = Metric.objects.all()
dates = Metric_Data.objects.all().values_list('start_date',flat=True).distinct().order_by('start_date')
data = []
for metric in metrics:
data.append(Metric_Data.objects.filter(metric=metric).order_by('start_date').values_list('count', flat=True))
return render_to_response('metric/show_all.html', {'dates': dates,
'metrics': metrics,
'data': data})
编辑:和模板
<table id="theTable" class="paginate-5">
<thead>
<tr>
<th>Dates</th>
{% for metric in metrics %}
<th>{{ metric.name }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for date in dates %}
<tr>
<td>{{date}}</td>
{% for metric in data %}
<td>{% get_index metric forloop.parentloop.counter0 %}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
我想最好的地方我在像这样的视图获取数据解决这个问题可能在模型中,但我不知道如何去解决这个问题。可能为日期创建一个表并在该表上执行查询?
想法非常感谢谢谢!
如何从数据库中提取数据? – Kugel 2009-11-25 02:10:05
更新视图:) – 2009-11-25 02:49:14
请同时显示调用此标签的模板。 – 2009-11-25 12:16:23