扩充Flask-SqlAlchemy声明性基础

时间:2014-03-27 10:03:52

标签: python sqlalchemy flask flask-sqlalchemy

我尝试了以下内容,似乎有效:

class BaseModel(db.Model):
    __abstract__ = True

    row_ver = db.Column(db.Integer, nullable=False)

    @declared_attr
    def __mapper_args__(cls):
        return {'version_id_col': cls.row_ver}

    def to_dict(self):
        res = dict()
        for c in self.__table__.columns:
            value = getattr(self, c.name)
            if isinstance(value, date):
                res[c.name] = value.isoformat()
            elif isinstance(value, uuid.UUID):
                res[c.name] = str(value)
            else:
                res[c.name] = value
        return res

class Account(BaseModel):
    __tablename__ = 'account'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)

我不确定它是否是扩充声明性基类的正确方法,即db.Model类。上面的代码有什么问题吗?

还相关:是否可以通过继承db.Model(它本身是声明性基础)来创建自定义声明性基类,如下所示:

class Base(db.Model):
    #some code here

from sqlalchemy.ext.declarative import declarative_base 
BaseModel = declarative_base(cls=Base)

class Account(BaseModel)
    #...

1 个答案:

答案 0 :(得分:0)

要自定义 db.Model,请声明 flask_sqlalchemy.Model 的超类并将其传递给 model_class,如下所示。

from flask_sqlalchemy import Model, SQLAlchemy


class AppModel(Model):
    row_ver = db.Column(db.Integer, nullable=False)


db = SQLAlchemy(model_class=AppModel)


class Account(db.Model):
    pass


class Thing(db.Model):
    pass

请注意,AccountThing 继承自 db.Model,而不是 AppModel