开发者

Google App Engine and Django templates: why do these two cases differ?

I'm new to Python, and I'm using Google App Engine to build a simple blog to help me learn it. I have the following test code:

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, }))

And a Django template that looks like this:

{% 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 %}

When I view this templated page in the browser, I get:

TypeError: 'Entry' object is not iterable

Changing the line {% for e in entries %} to {% for e in entries.all %} solves this problem, which is great.

However, this is the bit I don't understand; in another template (for the archive page), I pass in the same thing, a list of Entry objects:

entries = db.Query(Entry).order("-published").fetch(limit=100)
        self.response.out.write(template.render(templatePath + 'archive.django.html', { 'entries': entries, }))

With the template as follows:

{% extends "master.django.html" %}

{% block pagetitle %}Home Page{% endblock pagetitle %}

{% block content %}

<ul>

{% for entry in entries %}

<li>开发者_C百科<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 %}

This code works fine, without changing entries to entries.all; indeed if I do change it to that I get no output (no errors, just nothing at all).

Can someone explain why this is please?

Edit: I originally pasted the wrong piece of query code for the second example, which would probably have made things easier for people to give me an answer... changed it now.


You want to use .fetch(), not get():

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

get() returns only the first item that matches the query criteria, so instead of an iterable collection, you'll get one instance, and Entry object.

I can not explain why the second version does work. It really looks like it shouldn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜