[英]Flask-SQLAlchemy Abstract Base Model
In my Flask-SQLAlchemy App I want to add a few fields (created(by|on), changed(by|on)) to every Model/Table 在我的Flask-SQLAlchemy应用程序中,我想添加一些字段(创建(通过| on),更改(通过| on))到每个模型/表
my code right now 我的代码现在
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)
I am not sure if it's better to use Mixins or somehow extend the base db.Model (or if even there is a better way to do this). 我不确定是否最好使用Mixins或以某种方式扩展基础db.Model(或者即使有更好的方法来执行此操作)。
What (and why) is the best way to add such fields (created(by|on), changed(by|on)) to all my models? 什么(以及为什么)是添加这些字段(创建(通过| on),更改(通过| on))到我的所有模型的最佳方式?
Using __abstract__ . 使用__abstract__ 。
How do I declare a base model class in Flask-SQLAlchemy? 如何在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)
Both are pretty much the same. 两者都差不多。 Here is a Mixin that I use
这是我使用的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__)
and then 接着
class User(db.Model, ModelMixin):
""" attributes with _ are not exposed with public_view """
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.