加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:24:51 所属栏目:Python 来源:网络整理
导读:我们如何使用 Copy an entity in Google App Engine datastore in Python without knowing property names at ‘compile’ time中描述的函数clone_entity()将值复制到另一种实体中? (因为密钥也被复制,所以克隆发生在同一种类中,所以上述链接的解决方案不能
我们如何使用 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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读