Created
April 27, 2011 13:32
-
-
Save cklein/944248 to your computer and use it in GitHub Desktop.
ConverterProperty
This file contains 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 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