干得好:
def clone_entity(e, **extra_args):
"""Clones an entity, adding or overriding constructor attributes.
The cloned entity will have exactly the same property values as the original
entity, except where overridden. By default it will have no parent entity or
key name, unless supplied.
Args:
e: The entity to clone
extra_args: Keyword arguments to override from the cloned entity and pass
to the constructor.
Returns:
A cloned, possibly modified, copy of entity e.
"""
klass = e.__class__
props = dict((k, v.__get__(e, klass)) for k, v in klass.properties().iteritems())
props.update(extra_args)
return klass(**props)
用法示例:
b = clone_entity(a)
c = clone_entity(a, key_name='foo')
d = clone_entity(a, parent=a.key().parent())
将Gus的以下注释与对指定不同数据存储名称的属性的修复结合起来,以下代码可用于NDB:
def clone_entity(e, **extra_args):
klass = e.__class__
props = dict((v._code_name, v.__get__(e, klass)) for v in klass._properties.itervalues() if type(v) is not ndb.ComputedProperty)
props.update(extra_args)
return klass(**props)
用法示例(注释在NDB中key_name
变为id
):
b = clone_entity(a, id='new_id_here')
旁注:请参阅的使用,_code_name
以获取Python友好的属性名称。如果没有此属性,则类似的属性name = ndb.StringProperty('n')
将导致模型构造函数引发AttributeError: type object 'foo' has no attribute 'n'
。