mata answer is very clear on how to add a timestamp value. If you want to add the timestamp added automatically
on insert
and update
. You may consider have a BaseMixin class and register sqlalchemy event for every class. Example implementation is below:
class BaseMixin(object):
__table_args__ = {'mysql_engine': 'InnoDB'}
id = sa.Column(sa.Integer, primary_key=True)
created_at = sa.Column('created_at', sa.DateTime, nullable=False)
updated_at = sa.Column('updated_at', sa.DateTime, nullable=False)
@staticmethod
def create_time(mapper, connection, instance):
now = datetime.datetime.utcnow()
instance.created_at = now
instance.updated_at = now
@staticmethod
def update_time(mapper, connection, instance):
now = datetime.datetime.utcnow()
instance.updated_at = now
@classmethod
def register(cls):
sa.event.listen(cls, 'before_insert', cls.create_time)
sa.event.listen(cls, 'before_update', cls.update_time)
change your class HarvestSources(Base):
to class HarvestSources(Base, BaseMixin):
.
call HarvestSources.register()
on your model init. The updated_at
and created_at
column will update automatically.