Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

What (and why) is the best way to add such fields (created(by|on), changed(by|on)) to all my models?

like image 410
Daniel Kreiseder Avatar asked Jul 31 '14 09:07

Daniel Kreiseder


2 Answers

Using __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)
like image 113
yan Avatar answered Nov 02 '22 08:11

yan


Both are pretty much the same. Here is a Mixin that I use

  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)
like image 23
Lukasz Madon Avatar answered Nov 02 '22 07:11

Lukasz Madon