如何浅拷贝应用程序引擎模型实例来创建新的实例? [英] How to shallow copy app engine model instance to create new instance?

查看:138
本文介绍了如何浅拷贝应用程序引擎模型实例来创建新的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to implement a simple VersionedModel base model class for my app engine app. I'm looking for a pattern that does not involve explicitly choosing fields to copy.

我正在尝试这样的事情,但它是为了我的品味而做的,

I am trying out something like this, but it is to hacky for my taste and did not test it in the production environment yet.

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)

有没有人有更简洁的解决方案来保存应用版本的历史记录发动机型号?

Does anyone have a simpler cleaner solution for keeping history of versions for app engine models?

编辑:从tx中移出复制。 Thx @Adam Crossland的建议。

Moved copy out of tx. Thx @Adam Crossland for the suggestion.

推荐答案

查看属性模型类的静态方法。有了这个,你可以得到一个属性列表,并使用它来获取它们的值,如下所示:

Take a look at the properties static method on Model classes. With this, you can get a list of properties, and use that to get their values, something like this:

  @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)

这篇关于如何浅拷贝应用程序引擎模型实例来创建新的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆