首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何浅拷贝应用引擎模型实例来创建新实例?

如何浅拷贝应用引擎模型实例来创建新实例?
EN

Stack Overflow用户
提问于 2010-09-11 12:57:47
回答 1查看 371关注 0票数 0

我想为我的应用程序引擎应用程序实现一个简单的VersionedModel基模型类。我正在寻找一种模式,它不需要显式地选择要复制的字段。

我正在尝试这样的东西,但这是为了适应我的口味,还没有在生产环境中进行测试。

代码语言:javascript
复制
class VersionedModel(BaseModel):
    is_history_copy     = db.BooleanProperty(default=False)
    version             = db.IntegerProperty()
    created             = db.DateTimeProperty(auto_now_add=True)
    edited              = db.DateTimeProperty()
    user                = db.UserProperty(auto_current_user=True)

    def put(self, **kwargs):
        if self.is_history_copy:
            if self.is_saved():
                raise Exception, "History copies of %s are not allowed to change" % type(self).__name__
            return super(VersionedModel, self).put(**kwargs)
        if self.version is None:
            self.version = 1
        else:
            self.version = self.version +1
        self.edited =  datetime.now() # auto_now would also affect copies making them out of sync
        history_copy = copy.copy(self)
        history_copy.is_history_copy = True
        history_copy._key = None
        history_copy._key_name = None
        history_copy._entity = None
        history_copy._parent = self
        def tx():
            result = super(VersionedModel, self).put(**kwargs)
            history_copy._parent_key = self.key()
            history_copy.put()
            return result
        return db.run_in_transaction(tx)

有没有人有一个更简单的更清洁的解决方案来保存应用程序引擎模型的版本历史?

编辑:copy移出tx。Thx @Adam Crossland为您提供建议。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-09-13 10:36:38

看看模型类上的属性静态方法。使用此方法,您可以获得属性的列表,并使用该列表获取它们的值,如下所示:

代码语言:javascript
复制
  @classmethod
  def clone(cls, other, **kwargs):
    """Clones another entity."""
    klass = other.__class__
    properties = other.properties().items()
    kwargs.update((k, p.__get__(other, klass)) for k, p in properties)
    return cls(**kwargs)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3691064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档