App Engine 数据存储区中的可选参考字段
Optional reference field in app engine datastore
我有模型
class MyModel(ndb.Model):
foo = ndb.StringProperty()
class OtherModel(ndb.Model):
baz = ndb.StringProperty()
ref = ndb.KeyProperty(kind=MyModel)
我构建了一个视图,我可以在其中创建和修改这些模型实体,我希望 OtherModel
的 ref
字段是可选的,但是当我尝试提交并清空 ref
字段或删除它的旧值 我得到了 ndb.KeyProperty
的验证错误
我的更新逻辑是这样的:
for property in editableProperties:
# Lets suppose this parses values from a form in a request to the needed type
new_value = deserialize(property._kind, self.request.get(property._name))
setattr(item, property._name, new_value)
我尝试将 new_value 设置为 None
和空字符串。我怎样才能做到这一点?
如果您没有 Model
实体键来设置 ref
属性 就不要设置它 - 即不要将 属性 包含在您传递回数据存储以进行写入的实体值。如果这样做,您传递的 属性 值将接受健全性检查,并且会失败。
换句话说:根本不做
`setattr(item, property._name, new_value)`
当 new_value
不是键时,for ref
。而是按照这些思路做一些事情:
if hasattr(item, property._name):
delattr(item, property._name)
我有模型
class MyModel(ndb.Model):
foo = ndb.StringProperty()
class OtherModel(ndb.Model):
baz = ndb.StringProperty()
ref = ndb.KeyProperty(kind=MyModel)
我构建了一个视图,我可以在其中创建和修改这些模型实体,我希望 OtherModel
的 ref
字段是可选的,但是当我尝试提交并清空 ref
字段或删除它的旧值 我得到了 ndb.KeyProperty
的验证错误
我的更新逻辑是这样的:
for property in editableProperties:
# Lets suppose this parses values from a form in a request to the needed type
new_value = deserialize(property._kind, self.request.get(property._name))
setattr(item, property._name, new_value)
我尝试将 new_value 设置为 None
和空字符串。我怎样才能做到这一点?
如果您没有 Model
实体键来设置 ref
属性 就不要设置它 - 即不要将 属性 包含在您传递回数据存储以进行写入的实体值。如果这样做,您传递的 属性 值将接受健全性检查,并且会失败。
换句话说:根本不做
`setattr(item, property._name, new_value)`
当 new_value
不是键时,for ref
。而是按照这些思路做一些事情:
if hasattr(item, property._name):
delattr(item, property._name)