【问题标题】:Google App Engine and Django templates: why do these two cases differ?Google App Engine 和 Django 模板:为什么这两种情况不同?
【发布时间】: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


    【解决方案1】:

    你想使用 .fetch(),而不是 get():

    entries = db.Query(Entry).order("-published").fetch()
    comments = db.Query(Comment).order("published").fetch()
    

    get() 仅返回与查询条件匹配的第一项,因此您将获得一个实例和 Entry 对象,而不是可迭代集合。

    我无法解释为什么第二个版本可以工作。看起来确实不应该。

    【讨论】:

    • 你是对的,谢谢 - 第二个有效的原因是因为我复制了错误的代码:存档查询实际上是使用 fetch(limit=100) 正如你所说的。
    猜你喜欢
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 2018-09-08
    • 2017-05-20
    • 1970-01-01
    • 2019-11-08
    相关资源
    最近更新 更多