Auto updating columns don't work with SQLModel docs on updates #782
-
First Check
Commit to Help
Example Codefrom sqlmodel import SQLModel, Field, Session, create_engine
import datetime
engine = create_engine(...)
class SimpleTable(SQLModel, table=True):
version: int = Field(primary_key=True)
updated_at: datetime.datetime = Field(default_factory=datetime.datetime.utcnow, nullable=False)
def update_version() -> None:
"""Update the version of the table, where updated_at should update automatically"""
with Session(engine) as session:
stmt = select(SimpleTable)
tbl = session.exec(stmt).one()
tbl.version += 1
session.add(tbl)
session.commit() DescriptionWith the code above, which
The Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.14 Python VersionPython 3.9.8 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I don't know the answer here at all, but I am wondering if
would work? I'm just starting to use SQLModel and also trying to figure out where/how to best specify these things. |
Beta Was this translation helpful? Give feedback.
-
I think the following works and is a pretty clean solution?
|
Beta Was this translation helpful? Give feedback.
-
The following works: updated_at: datetime = Field(
sa_column_kwargs={
"server_default": func.now(),
"onupdate": func.now(),
},
nullable=False,
) Runnable code example in the details: import time
from datetime import datetime
from sqlmodel import Field, Session, SQLModel, create_engine, func
class SimpleTable(SQLModel, table=True):
version: int = Field(primary_key=True)
updated_at: datetime = Field(
sa_column_kwargs={
"server_default": func.now(),
"onupdate": func.now(),
},
nullable=False,
)
def main() -> None:
engine = create_engine(
"postgresql://user:mysecretpassword@localhost/some_db", echo=True
)
SQLModel.metadata.drop_all(engine)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(SimpleTable(version=1))
session.commit()
with Session(engine) as session:
o1 = session.get(SimpleTable, 1)
updated_at = o1.updated_at
time.sleep(0.1)
o1.version = 2
session.commit()
session.refresh(o1)
assert o1.updated_at > updated_at, "updated_at should be updated on commit"
if __name__ == "__main__":
main() |
Beta Was this translation helpful? Give feedback.
The following works:
Runnable code example in the details: