我有一些大的數據集,我循環顯示數據表。麻煩在於循環需要花費大量的時間,這是正確的,因爲這是一個內部工具,但我想改進它。更好的方式來循環瀏覽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