2012-01-28 63 views
5

我想我放鬆了我的心,爲什麼不做以下工作?App Engine將項目追加到ListProperty

class Parent(db.Model): 
    childrenKeys = db.ListProperty(str,indexed=False,default=None) 

p = Parent.get_or_insert(key_name='somekey') 
p.childrenKeys = p.childrenKeys.append('newchildkey') 
p.put() 

我得到這個錯誤:

BadValueError: Property childrenKeys is required 

的醫生說:

default is the default value for the list property. If None, the default is an empty list. A list property can define a custom validator to disallow the empty list.

所以路上,我看到它,我得到了默認的(空單),並附加一個新的價值,並保存它。

+0

在任何情況下,您可能都需要'StringListProperty'而不是'ListProperty(str)'。 (雖然如果這對你有用,但是最近的SDK可能會改變它們,使它們等同)。 – geoffspear 2012-01-29 00:51:02

回答

8

您應該刪除p.childrenKeys分配:

class Parent(db.Model): 
    childrenKeys = db.ListProperty(str,indexed=False,default=[]) 

p = Parent.get_or_insert('somekey') 
p.childrenKeys.append('newchkey') 
p.put() 
5

替換此:

p.childrenKeys = p.childrenKeys.append('newchildkey') 

與此:

p.childrenKeys.append('newchildkey') 

append()回報None,不能分配給p.childrenKeys

+0

這不是假設返回一個空的列表,因爲文檔說? Python中的空列表不能等於None,是嗎? – ofko 2012-01-28 23:23:39

+2

p.childrenKeys確實返回一個空的列表。 p.childrenKeys.append()返回None,因爲這是列表的append()方法的行爲。這裏的問題是將None分配給p.childrenKeys,這是ListProperty不允許的。 (您可以將空列表分配給ListProperty,它在數據存儲區內由沒有該名稱的屬性表示。) – 2012-01-29 00:22:40

+0

好的感謝解釋,我現在明白了。 – ofko 2012-01-29 00:27:29