The default field timestamp is set at the time the table was created, and not at the time the row was created

Using SQLAlchemy, alembic and postgres, when I try to set the column at the time the row was created, what I finally got is a field that by default refers to the time the table was created, and not the time the row was created.

Model Code:

datetime = sa.Column(sa.DateTime, nullable=False, server_default=func.now()) 

Alembic translates it into:

 sa.Column('datetime', sa.DateTime(), server_default='now()', nullable=False), 

And the column in Postgres:

 datetime | timestamp without time zone | not null default '2013-06-24 11:28:14.930524'::timestamp without time zone 

What should I do so that by default there is a line creation time?

+4
source share
1 answer

Aha, it worked - it seems you need to tell the server_default command if you are sending some kind of SQL that must be executed on the DBMS itself:

 from sqlalchemy import text class Test(db.Model): id = db.Column(db.Integer, primary_key=True) created = db.Column(db.DateTime, server_default=text('now()')) 

This generates:

 CREATE TABLE test ( id SERIAL NOT NULL, created TIMESTAMP WITHOUT TIME ZONE DEFAULT now(), PRIMARY KEY (id) ) 
+8
source

Source: https://habr.com/ru/post/1487868/


All Articles