App Engine 向 ListProperty 添加项

5 投票
2 回答
2962 浏览
提问于 2025-04-17 11:19

我觉得我快要疯了,为什么下面的代码不管用呢?

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,默认值就是一个空列表。列表属性可以定义一个自定义验证器来禁止空列表。

所以我理解的是,我得到了默认值(一个空列表),然后往里面添加了一个新值,最后保存了它。

2 个回答

5

把这个:

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

换成这个:

p.childrenKeys.append('newchildkey')

append() 这个函数返回的是 None,也就是说它不会给你一个值,所以你不能把它赋值给 p.childrenKeys

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()

撰写回答