2010-11-18 53 views
1

我剛剛開始學習Python,我正在慢慢掌握它,但我遇到了一個問題。不能在同一個Python文件中「定義」兩個數據庫嗎?

我正在嘗試使用Google的App Launcher SDK製作一個包含文章的簡單網站。

現在,一切都工作得很好,當我跟隨谷歌的網站的小指南,但現在我想創建另一個數據庫:

class Articles(db.Model): 
    title = db.TextProperty() 
    content = db.StringProperty(multiline=True) 
    date = db.DateTimeProperty(auto_now_add=True) 

沒有錯誤在這裏。 我再嘗試進行查詢,獲取所有信息,並張貼到模板:

class Articles(webapp.RequestHandler): 
    def get(self): 
     articles_query = Articles.all().order('-date') 
     articles = articles_query.fetch(10) 

     template_values = {'articles': articles} 

     path = os.path.join(os.path.dirname(__file__), 'articles.html') 
     self.response.out.write(template.render(path, template_values)) 

在這裏,我收到了一個錯誤:

line 45, in get 
    articles_query = Articles.all().order('-date') 
AttributeError: type object 'Articles' has no attribute 'all' 

我基本上覆制了谷歌的教程,只是更改查詢變量,但它不起作用。

任何想法?

回答

7

這並不是說您已經定義了兩個數據庫,而是您已經嘗試創建兩個名爲Articles的類。 Python無法將它們同時保存在頭上,所以一旦你製作了class Articles(webapp.RequestHandler),它就取代了class Articles(db.Model)

webapp.RequestHandler沒有all()方法,並且您尚未在第二個Articles類中定義一個方法。這就是爲什麼你會得到你所做的特定錯誤。

您應該爲您的課程使用不同的名稱。

+0

喔,我感到很慚愧..謝謝了很多,我怎麼可能犯這樣的錯誤? – Crembo 2010-11-18 14:33:30

+0

哦,很容易。我每天做3件這樣的事情。 :-) – 2010-11-18 15:29:27

2

我會重構這樣*

  1. class ArticlesHandler(webapp.RequestHandler)

  2. 重命名class Articles(webapp.RequestHandler)移動你的Articles模型稱爲models.py

  3. 添加from models import Articles一個單獨的文件webhandlers file

Handler後綴有助於區分Web處理程序中的規範類; 不同models.py模塊將您的模型實現隔離在一個位置,並且在您的項目變得更加複雜時可能非常有用。

*第1步是足以解決您的具體問題

相關問題