Using SQLAlchemy, alembic and postgres, when trying to set a column to the row creation time what I finally get is a field that defaults to the time when the table itself was created, instead of the time when the row was created.
Model code:
datetime = sa.Column(sa.DateTime, nullable=False, server_default=func.now())
Alembic translates it to:
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 the default is the row creation time?
TIMESTAMP has a default of 0 unless defined with the NULL attribute, in which case the default is NULL .
We can provide the default value of the current timestamp to a column in PostgreSQL by using the default keyword. We can provide default current timestamp value to the column at the time of table creation.
Use of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP is specific to TIMESTAMP. The DEFAULT clause also can be used to specify a constant (nonautomatic) default value; for example, DEFAULT 0 or DEFAULT '2000-01-01 00:00:00'.
We can set the now() function as a default value with the help of dynamic default. First, we will create a table with data type” datetime”. After that, we will set now() as the default value for column “MyTime” as shown below. Creating a table.
Aha, worked it out-- seems you need to tell the server_default command if you're sending in some SQL that needs to 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()'))
That generates:
CREATE TABLE test (
id SERIAL NOT NULL,
created TIMESTAMP WITHOUT TIME ZONE DEFAULT now(),
PRIMARY KEY (id)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With