【发布时间】:2011-01-08 14:00:52
【问题描述】:
我是 Python 新手,我正在使用 Google App Engine 构建一个简单的博客来帮助我学习它。我有以下测试代码:
entries = db.Query(Entry).order("-published").get()
comments = db.Query(Comment).order("published").get()
self.response.out.write(template.render(templatePath + 'test.django.html', { 'entries': entries, 'comments': comments, }))
还有一个看起来像这样的 Django 模板:
{% extends "master.django.html" %}
{% block pagetitle %}Test Page{% endblock pagetitle %}
{% block content %}
{% for e in entries %}
<p><a href="/post/{{ e.slug }}/">{{ e.title|escape }} - {{ e.published|date:"jS o\f F Y" }}</p>
{% endfor %}
{% for c in comments.all %}
<p>{{ c.authorname }} {{ c.published|date:"d/m/Y h:i" }}</p>
{% endfor %}
{% endblock content %}
当我在浏览器中查看这个模板页面时,我得到:
TypeError: 'Entry' object is not iterable
将{% for e in entries %}这一行改成{% for e in entries.all %}就解决了这个问题,太好了。
但是,这是我不明白的一点;在另一个模板(用于存档页面)中,我传入了同样的东西,一个 Entry 对象列表:
entries = db.Query(Entry).order("-published").fetch(limit=100)
self.response.out.write(template.render(templatePath + 'archive.django.html', { 'entries': entries, }))
模板如下:
{% extends "master.django.html" %}
{% block pagetitle %}Home Page{% endblock pagetitle %}
{% block content %}
<ul>
{% for entry in entries %}
<li><a href="/post/{{ entry.slug }}/">{{ entry.title|escape }} <span>{{ entry.published|date:"jS o\f F Y" }}</a>{% if admin %} - <a href="/compose/?key={{ entry.key }}">Edit Post</a>{% endif %}</span></li>
{% endfor %}
{% endblock content %}
这段代码运行良好,没有将entries 更改为entries.all;确实,如果我 确实 将其更改为没有输出(没有错误,什么都没有)。
有人能解释一下这是为什么吗?
编辑:我最初为第二个示例粘贴了错误的查询代码,这可能会让人们更容易给我答案...现在更改它。
【问题讨论】:
标签: python google-app-engine django-templates