2010-05-07 82 views
3
class Thread(db.Model): 
    members = db.StringListProperty() 

    def user_is_member(self, user): 
    return str(user) in self.members 

GAE錯誤:AttributeError的: 'NoneType' 對象有沒有屬性 'user_is_member'

thread = Thread.get(db.Key.from_path('Thread', int(id))) 
is_member = thread.user_is_member(user) 

但錯誤是:

Traceback (most recent call last): 
    File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__ 
    handler.get(*groups) 
    File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 62, in check_login 
    handler_method(self, *args) 
    File "D:\zjm_code\forum_blog_gae\main.py", line 222, in get 
    is_member = thread.user_is_member(user) 
AttributeError: 'NoneType' object has no attribute 'user_is_member' 

爲什麼呢?

感謝

+0

貌似db.Key.from_path(「線」,INT (id))不會創建有效的密鑰。 – systempuntoout 2010-05-07 09:24:16

回答

6

你試圖通過按鍵獲取的實體,但與該鍵無實體存在,因此獲得()將返回無。你需要檢查試圖採取行動,那麼在此之前,一個有效的實體返回,就像這樣:

thread = Thread.get(db.Key.from_path('Thread', int(id))) 
if thread: 
    is_member = thread.user_is_member(user) 
else: 
    is_member = False 

或等價:

thread = Thread.get(db.Key.from_path('Thread', int(id))) 
is_member = thread.user_is_member(user) if thread else False 
+0

或者'is_member = thread和thread.user_is_member(user)' – 2010-05-07 10:54:09

+0

@Thomas:不,因爲如果線程爲None,那麼將返回None(而不是False)。 – 2010-05-07 16:31:28

+0

那又如何?沒有一個是完全可以接受的假值。 – 2010-05-07 16:59:28

相關問題