Created
September 16, 2011 17:00
-
-
Save mdeous/1222548 to your computer and use it in GitHub Desktop.
mixin for auto populating columns in sqlalchemy models
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 AutoInitModelMixin(object): | |
| """ | |
| Mixin for populating models' columns automatically (no need to | |
| define an __init__ method) and set the default value if any. | |
| Also sets the model's id and __tablename__ automatically. | |
| """ | |
| id = db.Column(db.Integer, primary_key=True) | |
| # use the lowercased class name as the __tablename__ | |
| @declared_attr | |
| def __tablename__(cls): | |
| return cls.__name__.lower() | |
| def __init__(self, *args, **kwargs): | |
| for attr in (a for a in dir(self) if not a.startswith('_')): | |
| attr_obj = getattr(self, attr) | |
| if isinstance(attr_obj, db.Column): | |
| if attr in kwargs: | |
| setattr(self, attr, kwargs[attr]) | |
| else: | |
| if hasattr(attr_obj, 'default'): | |
| if callable(attr_obj.default): | |
| setattr(self, attr, attr_obj.default()) | |
| else: | |
| setattr(self, attr, attr_obj.default) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment