Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add datetime column with default value

Tags:

python

alembic

I'm trying to write an alembic migration to add a datetime column to a table. I want all existing rows to have a default time of right now and future rows to default to the time they were created. I've tried server_default='now()', which sets all existing rows to right now, but new rows seem to get this same time. How do I set the default so new rows get the current time?

like image 424
Cathal Avatar asked May 07 '14 08:05

Cathal


1 Answers

The issue is that the default is set to the result of now(), not the execution of it, so the default will be the exact time it was set, rather than the current time at insert. Use sa.func.current_timestamp() to set it to that function, rather than the result of that function.

def upgrade():
    op.add_column('my_table', sa.Column('my_column', sa.DateTime,
            server_default=sa.func.current_timestamp()))
like image 188
davidism Avatar answered Oct 14 '22 00:10

davidism