pythonsqlalchemypython-typing

How do I do server-side default value when using SQLAlchemy 2.0 with dataclass?


I have a column defined as ts timestamp with time zone not null default current_timestamp. I want to SQLAlchemy to not insert this value on the client side when inserting data at the same time passes type checking.

class Base(MappedAsDataclass, DeclarativeBase):
  pass

class MyTable(Base):
  ts: Mapped[datetime.datetime] = mapped_column(DateTime, init=False, nullable=False)

This doesn't work because SQLAlchemy is trying to insert a null value. I've tried various *default arguments but they don't work.


Solution

  • Looks like server_default is what you are looking for: link 1 and link 2

    something like

    mapped_column(DateTime, server_default=text("NOW()"), init=False, nullable=False)