App Engine如何将项目添加到ListProperty中

5

我觉得我要疯了,为什么下面的代码不起作用?

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 是列表属性的默认值。如果为 None,则默认为空列表。列表属性可以定义自定义验证器来禁止空列表。

所以我理解的方式是,我得到了默认值(一个空列表),并向其中添加新值,然后保存它。


你可能需要一个 StringListProperty 而不是 ListProperty(str),无论如何。 (尽管如果这对您有用,最近的 SDK 中可能已更改使它们等效)。 - Wooble
2个回答

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


它不应该返回一个空列表吗,就像文档中说的那样?在Python中,空列表难道等同于None吗? - userBG
2
p.childrenKeys 返回一个空列表。 p.childrenKeys.append() 返回 None,因为这是列表的 append() 方法的行为。 这里的问题是将 None 分配给 p.childrenKeys,这是不允许的 ListProperty。 (您可以将空列表分配给 ListProperty,在数据存储中,这表示没有该名称的属性。) - Dan Sanderson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接