Am I able to set a SQL field default value or binding? #1469
-
First Check
Commit to Help
Example Codecreated_at: datetime.datetime = datetime.datetime.now() DescriptionI am trying to figure out a way to set the SQL column property "Default Value or Binding" via an SQLModel model. I'm trying to make it so that a datetime field defaults to GETUTCDATE(). I know I can do something like "created_at: datetime.datetime = datetime.datetime.now()" but that doesn't exactly apply the default to the column itself. I want to create the table with this default on the field so no matter how the data gets into that table, the field will always will in with GETUTCDATE(). Is there a way to do this in SQLModel? Thanks. Operating SystemWindows Operating System DetailsNo response SQLModel Version0.0.6 Python Version3.9.12 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
First, datetime.now is not the same as GETUTCDATE(), you should use datetime.utcnow. from datetime import datetime
from sqlalchemy import text
from sqlmodel import Field
...
created_at: datetime = Field(default_factory=datetime.utcnow, sa_column_kwargs={"server_default": text("GETUTCDATE()")}) |
Beta Was this translation helpful? Give feedback.
-
Thanks a ton. This was exactly what I was looking for. |
Beta Was this translation helpful? Give feedback.
First, datetime.now is not the same as GETUTCDATE(), you should use datetime.utcnow.
Second, to solve your problem you need to add additional arguments to the Column class of the sqlalchemy: