create and update timestamp in DB

I have following defined in my sqlalchemy models file.

class CommonColumns(Base):
 __abstract__ = True
 _created = Column(DateTime,
 _updated = Column(DateTime,,

I then derive most of my classes from CommonColumns This automatically inserts the creation and updation timestamps for the each row.

But this works for the records created via the python/sqlalchemy script using db.session.add(...)

Recently I needed to quickly insert records directly from psql prompt. Something like :

insert into user (name, age) values ('John', 25);

Since my models file does not have server_default, the record created from psql ends up with null values in the _created and _updated columns

That is when I discovered, that I can use CURRENT_TIMESTAMP in postgres. (mysql may have slightly different function name) Something like :

insert into user (name, age, _created, _updated) values ('John', 25, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);


Comments powered by Disqus
Google Analytics Alternative