Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a base model class in Flask-SQLAlchemy?

Tags:

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) 
like image 217
Max L. Avatar asked Apr 10 '14 00:04

Max L.


People also ask

What is a base class in SQLAlchemy?

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.

How do you add a SQLAlchemy to a Flask?

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.

What is a model in 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.


1 Answers

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) 
like image 92
dirn Avatar answered Oct 15 '22 12:10

dirn