我想遍历放置在列表中的一些对象并获取每个对象的统计信息。
我正在使用Django 1.11.16
用户可以选择一个或多个出版物,我会在列表中显示每个出版物的一些统计信息。
我有一个看起来像这样的视图部分:
def get_context_data(self, **kwargs):
publication_list = self.request.GET.getlist('publication_list')
publication_selected = Publication.objects.filter(id__in=publication_list)
download_all_period = Download.objects.values('usage', 'doc__publication__pub_id') \
.filter(
doc__publication__id__in=publication_list) \
.filter(
Q(creation_date__gte=start_date) & Q(creation_date__lte=end_date))\
.aggregate(
nusage=Sum('usage'))
request_all_period = Download.objects.values('doc__publication__pub_id')\
.filter(
doc__publication__id__in=publication_list)\
.filter(
Q(creation_date__gte=start_date) & Q(creation_date__lte=end_date))
all_period_list = zip(publication_selected, download_all_period, request_all_period)
context_data['publication_list'] = publication_list
context_data['publication_selected'] = publication_selected
context_data['download_all_period'] = download_all_period
context_data['request_all_period'] = request_all_period
context_data['all_period_list'] = all_period_list
return context_data
然后我有一个带有桌子的模板。因此,我想遍历列表中的每个元素,以便为每个元素创建一行:
{% for publication_selected, download_all_period, request_all_period in all_period_list %}
{% if download_all_period.nusage %}
<tr>
<td>{{ start_date|date:"Y/m/d" }} to {{ end_date|date:"Y/m/d" }}</td>
<td>{{ publication_selected }}</td>
<td><span class="badge alert-danger">{{ download_all_period.nusage }}</span> / <span
class="badge alert-info">{{ request_all_period.count }}</span></td>
</tr>
{% else %}
<tr>
<td>{{ start_date|date:"d/m/Y" }} to {{ end_date|date:"d/m/Y" }}</td>
<td>{{ publication_selected }}</td>
<td>{% trans 'No downloads/No requests' %}</td>
</tr>
{% endif %}
{% endfor %}
它仅显示列表中的最后一个对象,并且我始终位于{% else %}
部分中,而我可以为该特定对象打印统计信息。
答案 0 :(得分:1)
您必须在download_all_period查询中使用ANNOTATE而不是AGGREGATE,