53

I am writing a migration in alembic but seems impossible to me the change the value of server_defaults from something to nothing.

My code:

op.alter_column("foo", sa.Column("bar", sa.DateTime(timezone=False), server_default=None, nullable=True))

If i check after the migration the default is still NOW()

tapioco123
  • 3,235
  • 10
  • 36
  • 42

2 Answers2

84

To rename a column as of Alembic 0.9.5 I had to alter my migration to read as follows:

op.alter_column('my_table', 'old_col_name', nullable=False, new_column_name='new_col_name')
Iain Hunter
  • 4,319
  • 1
  • 27
  • 13
  • 2
    Note you also must specify `existing_type` to run `alter_column` command – Mugen Feb 27 '19 at 12:46
  • 4
    It seems that the `existing_type` argument is only mandatory in some circumstances, such as for certain MySQL operations. [The docs](https://alembic.sqlalchemy.org/en/latest/ops.html?highlight=insert#alembic.operations.Operations.alter_column.params.existing_type) have more. – Nick K9 Mar 04 '19 at 16:48
  • 1
    If you want to support sqlite you'll need to do this in a batch: `with op.batch_alter_table('my_table', schema=None) as batch_op: batch_op.alter_column('old_col_name', new_column_name='new_col_name')` – Charles L. Feb 18 '21 at 18:10
  • It is not necessary to specify `existing_type` if you use MariaDB , in my case, I modify data type of an existing column by passing the argument `type_` to `alter_column()` and it works well. – Ham Jun 21 '21 at 08:32
22

That's not how op.alter_column() works. Pass it arguments about what to change, not a new sa.Column instance.

op.alter_column('my_table', 'my_column', server_default=None)
davidism
  • 121,510
  • 29
  • 395
  • 339