0

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

我正在尝试这样的东西,但它对我的口味来说太老套了,还没有在生产环境中测试它。

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)

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

编辑:搬出copytx。感谢@Adam Crossland 的建议。

4

1 回答 1

2

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

  @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)
于 2010-09-13T10:36:38.630 回答