微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将GAE中的所有实体复制到另一种,而不显式调用每个属性

我们如何使用 Copy an entity in Google App Engine datastore in Python without knowing property names at ‘compile’ time中描述的函数clone_entity()将值复制到另一种实体中? (因为密钥也被复制,所以克隆发生在同一种类中,所以上述链接解决方案不能用于此特定目的!)

试过以下(和其他变化但无济于事)

query = db.GqlQuery("SELECT * FROM OrigKind")
results = query.fetch(10);

for user in results:
    new_entry = models.NewKind()
    new_entry_complete_key = new_entry.put()
    new_entry = clone_entity(user,Key=new_entry_complete_key)
    new_entry.put()

(需要将所有实体从OrigKind复制到NewKind)

解决方法

您需要修改版本的 clone_entity

original clone method的一些陷阱在原始实施的答案中讨论过.

def clone_entity(e,to_klass,**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 to_klass(**props)

# Use the clone method
query = db.GqlQuery("SELECT * FROM OrigKind")
results = query.fetch(10);

for user in results:
    new_entry = clone_entity(user,NewKind)
    new_entry.put()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐