Skip to content

Instantly share code, notes, and snippets.

@cklein
Created April 27, 2011 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cklein/944248 to your computer and use it in GitHub Desktop.
Save cklein/944248 to your computer and use it in GitHub Desktop.
ConverterProperty
class ConverterProperty(db.Property):
"""Property class for converting data
Example:
Given a class MyModel which an IntegerProperty that should be converted to a StringProperty:
class MyModel(db.Model):
value = IntegerProperty()
In the conversion step the model would look like this:
class MyModel(db.Model):
value = ConverterProperty(lambda x: str(x))
After all data has been converted, you can replace the property:
class MyModel(db.Model):
value = StringProperty()
"""
def __init__(self, fnc, **kwargs):
"""Positional argument `fnc` is the converter function that is called for the property value"""
super(ConverterProperty, self).__init__(**kwargs)
self.convert = fnc
def get_value_for_datastore(self, model_instance):
"""Get value from property to send to datastore."""
value = super(ConverterProperty, self).get_value_for_datastore(model_instance)
return self.convert(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment