Dan*_*der 6 python flask flask-sqlalchemy
在我的Flask-SQLAlchemy应用程序中,我想添加一些字段(创建(通过| on),更改(通过| 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)
Run Code Online (Sandbox Code Playgroud)
我不确定是否最好使用Mixins或以某种方式扩展基础db.Model(或者即使有更好的方法来执行此操作).
什么(以及为什么)是添加这些字段(创建(通过| on),更改(通过| on))到我的所有模型的最佳方式?
小智 8
使用__abstract__.
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)
Run Code Online (Sandbox Code Playgroud)
两者都差不多.这是我使用的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__)
Run Code Online (Sandbox Code Playgroud)
然后
class User(db.Model, ModelMixin):
""" attributes with _ are not exposed with public_view """
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4183 次 |
| 最近记录: |