拆分字典对象



我正在构建一个博客应用程序,我做了一个queryset,这是blog date以来每天的showing blog date and likes,但它显示在dictionary中,我试图在表中显示两个不同的实例,如。

tbody> <<tr>
博客日期 点赞数
20 9月。6喜欢
9月21日2个Likes
9月22日4个赞

您可以使用TruncDate来获取日期:

from django.db.models import Count
from django.db.models.functions import TruncDate
totals = blogpost.likes_set.filter(
blogpost__date=blogpost.date,
).values(
date=TruncDate('blogpost__date')
).annotate(
n=Count('pk')
).order_by('date')

如果你把这个传递给上下文,你可以用:

<table>
<thead>
<th>Blog Date</th><th>Likes</th>
</thead>
<tbody>
{% for item in totals %}
<tr>
<td>{{item.date|date:"F, d"}}</td><td>{{ item.n }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{d['date']: d['n'] for d in totals}

创建一个键为日期,值为值的字典。虽然可以从中提取数据,但这没有任何意义,特别是当您将它们存储在列表中时。但是你已经在总数中有了很好的结构化输出,所以直接使用它,而不是把它全部包装在字典的Counter中(顺便说一句,我不知道你为什么要使用Counter)。

return render(request, 'page.html', {"results": totals})

这样数据就可以很好地传递到模板。然后你的html模板只需要迭代结果:

{% for result in results %}
<tr>
<td>result.date</td><td>result.n</td>
</tr>
{% endfor %}

最新更新