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

点点圈 提交于 2019-11-27 01:49:50

问题


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)

回答1:


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)


来源:https://stackoverflow.com/questions/22976445/how-do-i-declare-a-base-model-class-in-flask-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!