2010-01-23 27 views
1

我是新來的Python,和我使用谷歌應用程序引擎構建一個簡單的博客,以幫助我學習它。我有以下的測試代碼:Google App Engine和Django模板:爲什麼這兩種情況有所不同?

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 %}解決了這個問題,這很好。

但是,這是我不明白的一點;在另一個模板(存檔網頁),我通過在同樣的事情,入學對象的列表:

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;確實如果我改變它,我得不到輸出(沒有錯誤,只是沒有)。

有人能解釋這是爲什麼嗎?

編輯:我本來粘貼在第二個例子中的錯件的查詢代碼,這將有可能使事情更容易爲人們給我一個答案......現在改變了它。

回答

2

你想用.fetch(),不能獲得():

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

get()返回只有符合查詢條件的第一個項目,所以不是一個可迭代的收集,你會得到一個實例和Entry對象。

我無法解釋爲什麼第二個版本不工作。它看起來應該不是。

+0

你說得對,謝謝 - ,第二個作品的原因是因爲我抄錯的代碼:檔案查詢被實際使用取(上限爲100)如你所說。 – 2010-01-23 17:04:35

相關問題