onupdate
functionality not available?
#990
-
First Check
Commit to Help
Example Codefrom sqlalchemy import func, DateTime
# Working with FastAPI / sqlalchemy
created_at = mapped_column(DateTime, server_default=func.now())
updated_at = mapped_column(DateTime, onupdate=func.now())
created_at = Column(DateTime, server_default=func.now())
updated_at = Column(DateTime, onupdate=func.now())
# SQLModel
created_at: datetime | None = Field(default=func.now())
updated_at = ?????????????? DescriptionI would like my models / tables to have a When working with FastAPI / sqlalchemy I have multple options to specify that using
As far as I have seen in the docs there is only a
but there is no I tried to integrete the sqlalchemy fields into SQLModel but this did not work. Operating SystemWindows Operating System DetailsNo response SQLModel Version0.0.19 Python Version3.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
You can use class UpdatedAt(SQLModel):
updated_at: Optional[datetime] = Field(
default=None,
sa_type=sa.DateTime(timezone=True),
sa_column_kwargs={
'onupdate': sa.func.now(),
'server_default': sa.func.now(),
},
) |
Beta Was this translation helpful? Give feedback.
-
Would be nice to have native support in created_at: datetime = Field(sa_column=Column(DateTime, default=func.now()))
updated_at: datetime = Field(sa_column=Column(DateTime, default=func.now(), onupdate=func.now())) |
Beta Was this translation helpful? Give feedback.
-
I set the updater id and update time in the add function👇🏻 from datetime import datetime
from sqlmodel import Session as _Session
class Session(_Session):
def add(self, instance: BaseTable, *args, **kwargs) -> None:
user_id = self.info['user_id']
if isinstance(instance, CreatorUpdaterMixin) and user_id:
if not instance.creator:
instance.created_by = user_id
instance.create_at = datetime.now()
else:
instance.updated_by = user_id
instance.update_at = datetime.now() |
Beta Was this translation helpful? Give feedback.
You can use
sa_column_kwargs
. My example of using as an mixin class