I would like to declare a base class that all other schema objects can inherit from, 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 have to repeat the declaration of the two columns.
How would 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)
A base class stores a catlog of classes and mapped tables in the Declarative system. This is called as the declarative base class. There will be usually just one instance of this base in a commonly imported module. The declarative_base() function is used to create base class. This function is defined in sqlalchemy.
Step 1 - Install the Flask-SQLAlchemy extension. Step 2 - You need to import the SQLAlchemy class from this module. Step 3 - Now create a Flask application object and set the URI for the database to use. Step 4 - then use the application object as a parameter to create an object of class SQLAlchemy.
Model is a class within the Flask-SQLAlchemy project. Flask-SQLAlchemy makes it easier to use SQLAlchemy within a Flask application. SQLAlchemy is used to read, write, query and delete persistent data in a relational database through SQL or the object-relational mapper (ORM) interface built into the project.
SQLAlchemy offers a directive called __abstract__
. You can use it to tell SQLAlchemy not to create the table for a particular model. That model can be used as your 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With