I have following defined in my sqlalchemy models file.

1
2
3
4
class CommonColumns(Base):
 __abstract__ = True
 _created = Column(DateTime, default=func.now())
 _updated = Column(DateTime, default=func.now(), onupdate=func.now())

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 :

1
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 :

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