【问题标题】:Flask-SQLAlchemy Abstract Base ModelFlask-SQLAlchemy 抽象基础模型
【发布时间】:2014-07-31 09:53:18
【问题描述】:

在我的 Flask-SQLAlchemy 应用程序中,我想向每个模型/表添加一些字段(created(by|on)、changed(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 是否更好(或者是否有更好的方法来做到这一点)。

向我的所有模型添加此类字段(created(by|on)、changed(by|on))的最佳方式是什么(以及为什么)?

【问题讨论】:

标签: python flask flask-sqlalchemy


【解决方案1】:

使用 __abstract__。

How do I declare a base model class in 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)

【讨论】:

    【解决方案2】:

    两者几乎相同。这是我使用的一个 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-27
      • 2018-02-18
      • 2013-10-21
      • 2014-05-06
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      相关资源
      最近更新 更多