Flask SQLAlchemy:如何扩展基础Model类?

时间:2016-05-29 23:06:16

标签: python flask sqlalchemy

在Flask / SQLAlchemy中,我们使用servlet中的Model类,而不是flask_sqlalchemy中的sqlalchemy类,如下所示:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

class Foo(db.Model):
    bar = db.Column(db.String)

我有一个功能,我添加到我定义的每个模型。我想扩展一些基类并在那里添加函数,所以我不必重复自己。使用普通的SQLAlchemy,我们可以扩展声明性基类来执行此操作。我们如何在flask_sqlalchemy中实现这一目标?

如果不提出db.Model类,则无法进行扩展:

  

InvalidRequestError:类未指定 tablename ,并且不从现有的表映射类继承。

1 个答案:

答案 0 :(得分:9)

您可以通过设置 public List<MonthlyPoint> groupByMonth(ChartRequest request){ SQLQuery query = getSession().createSQLQuery("SELECT \n" + "sum(this_.amount) as amount, \n" + "extract(month from this_.fecha) as month, \n" + "extract(year from this_.fecha) as year\n" + "FROM jornada this_ \n" + "GROUP BY \n" + "month, \n" + "year \n" + "ORDER BY \n" + "year asc, \n" + "month asc"); query.setResultTransformer(Transformers.aliasToBean(MonthlyPoint.class)); return query.list(); } public class MonthlyPoint { private Double year; private Double month; private Double amount; //-- getters and setters here -- } 来修复错误。我修改了你的例子:

__abstract__ = True
the documentation中描述了

from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQLAlchemy(app) class Foo(db.Model): __abstract__ = True bar = db.Column(db.String) 。或者,您可以使用mixin class

需要更多代码,您还可以通过继承__abstract__并覆盖其SQLAlchemy方法来覆盖声明性基类。例如:

make_declarative_base()

然后像往常一样继承from flask import Flask from flask_sqlalchemy import SQLAlchemy, Model, _BoundDeclarativeMeta, _QueryProperty from sqlalchemy.ext.declarative import declarative_base app = Flask(__name__) class MyModel(Model): ... class MySQLAlchemy(SQLAlchemy): def make_declarative_base(self, metadata=None): base = declarative_base(cls=MyModel, name='MyModel', metadata=metadata, metaclass=_BoundDeclarativeMeta) base.query = _QueryProperty(self) return base db = MySQLAlchemy(app) “。