Flask-SQLAlchemy抽象基模型

15 投票
2 回答
13830 浏览
提问于 2025-04-18 15:28

在我的Flask-SQLAlchemy应用中,我想给每个模型/表添加一些字段(创建者(by)、创建时间(on)、修改者(by)、修改时间(on))。

我现在的代码是

from .. import db


class Brand(db.Model):
    __tablename__ = 'md_brands'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, nullable=False)

    def __repr__(self):
        return u'<Brand {}>'.format(self.name)

我不太确定是使用Mixins更好,还是以某种方式扩展基础的db.Model(或者是否还有更好的方法来做到这一点)。

有什么方法(以及为什么)是将这些字段(创建者(by)、创建时间(on)、修改者(by)、修改时间(on))添加到我所有模型的最佳方式?

2 个回答

41

使用 __abstract__

我该如何在Flask-SQLAlchemy中声明一个基础模型类?

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)
9

这两者基本上是一样的。这里有一个我用的混合类(Mixin)

  class ModelMixin(object):
      def __repr__(self):
          return unicode(self.__dict__)

      @property
      def public_view(self):
          """return dict without private fields like password"""
          return model_to_dict(self, self.__class__)  

然后

class User(db.Model, ModelMixin):
      """ attributes with _  are not exposed with public_view """
      __tablename__ = "users"
      id = db.Column(db.Integer, primary_key=True)

撰写回答