SQLAlchemy Tutorial 2 :Before Insert Before Update in SQLAlchemy

SQLAlchemy Tutorial 2 :Before Insert Before Update in SQLAlchemy

Please check my previous post for declarative mysql tables in SQLAlchemy:

how can i define and create my MySQL tables with SQLAlchemy ORM?

I have 4 fields in my all database tables for change logs. But i need automatic timestamp values for created_at and updated_at columns. For this purposes you can use mapper extension in SQLAlchemy.

Here base extension class

class BaseExtension(MapperExtension):
    """Base entension class for all entity """

    def before_insert(self, mapper, connection, instance):
        """ set the created_at  """
        instance.created_at = datetime.now()

    def before_update(self, mapper, connection, instance):
        """ set the updated_at  """
        instance.updated_at = datetime.now()

and here country entity

class Country(Base):
    """ Country entity class """
    __tablename__ = 'country'
    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8'
    # mapper extension declarative for before insert and before update
    __mapper_args__ = { 'extension': BaseExtension() }

    # this field is in model "id", in db "country_id"
    # not null and auto_increment settings with "primary_key"
    id = Column('country_id', BIGINT(unsigned=True), primary_key=True)
    code = Column(VARCHAR(10), nullable=False, unique=True)
    name = Column(VARCHAR(100), nullable=False, unique=True)
    created_by_user = Column(VARCHAR(50))
    created_at = Column(DATETIME)
    updated_by_user = Column(VARCHAR(50))
    updated_at = Column(DATETIME)

    def __init__(self, code, name):
        self.code = code
        self.name = name

Leave a Reply