Created
February 28, 2012 18:36
-
-
Save gregorynicholas/1934201 to your computer and use it in GitHub Desktop.
shallow copy app engine model instance to create new instance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
@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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment