如何将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()

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...