How to declare a model base class in Flask-SQLAlchemy?

I would like to declare a base class that all other schema objects can inherit, for example:

class Base(db.Model): created_on = db.Column(db.DateTime, default=db.func.now()) updated_on = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) 

Then all other schema objects can inherit from it and not repeat the declaration of two columns.

How do I do this in Flask-SQLAlchemy?

 from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key = True) email = db.Column(db.String(255), unique = True) 
+8
flask flask-sqlalchemy sqlalchemy
source share
1 answer

SQLAlchemy offers a directive called __abstract__ . You can use it so that SQLAlchemy does not create a table for a specific model. This model can be used as a base class.

 from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class Base(db.Model): __abstract__ = True created_on = db.Column(db.DateTime, default=db.func.now()) updated_on = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) class User(Base): __tablename__ = 'users' id = db.Column(db.Integer, primary_key = True) email = db.Column(db.String(255), unique = True) 
+30
source share

All Articles