Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field default timestamp set to table creation time instead of row creation time

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?

like image 256
Artur Soler Avatar asked Jun 24 '13 11:06

Artur Soler


People also ask

What is default timestamp in SQL?

TIMESTAMP has a default of 0 unless defined with the NULL attribute, in which case the default is NULL .

How do I set the default time in PostgreSQL?

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.

How do I add a default value to a timestamp column?

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'.

How do I change the default date and time in MySQL?

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.


1 Answers

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)
)
like image 176
Doobeh Avatar answered Oct 08 '22 20:10

Doobeh