我正在尝试使用 Django 构建一个简单的博客,并尝试显示博客帖子和与帖子相关的评论数。不幸的是,我在让我的字典打印出值时遇到了麻烦——或者至少在我想要的地方。
在我的 views.h 文件中:
class IndexView(generic.TemplateView):
template_name = 'blogs/index.html'
num_comments = { }
def get_blogs(self):
"""
Returns the last 5 published blog posts.
"""
blogs = BlogPost.objects.filter(
pub_date__lte = timezone.now()
).order_by('-pub_date')[:5]
for blog in blogs:
# Setting our num_comments dictionary by getting
# the number of comments from a particular blog post
self.num_comments[blog.id] = len(Comment.objects.filter(blog_post = blog.id))
return blogs
在我的 index.html 文件中:
{{ view.num_comments }}
{% if view.get_blogs %}
{% for blog in view.get_blogs %}
<div>
<h1>{{ blog.post_title }}</h1>
<p>{{ blog.post_text }}</p>
<ul>
{{ blog.id }}
{{ view.num_comments }}
{% for key, value in view.num_comments %}
<li>
{{ key }} <-- Does not display
{{ value }} <-- Does not display
</li>
{% endfor %}
</ul>
</div>
{% endfor %}
{% else %}
<p>No blogs are available.</p>
{% endif %}
在我显式调用 {{ view.num_comments }} 的地方,显示了正确的字典。知道为什么我的字典没有正确获取键值对吗?谢谢。
请您参考如下方法:
你应该使用 .items()访问键值对的方法:
{% for key, value in view.num_comments.items %}
另见 Django documentation 中的第三个示例.
