sqlmodel
sqlmodel copied to clipboard
Am I able to set a SQL field default value or binding?
First Check
- [X] I added a very descriptive title to this issue.
- [X] I used the GitHub search to find a similar issue and didn't find it.
- [X] I searched the SQLModel documentation, with the integrated search.
- [X] I already searched in Google "How to X in SQLModel" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to SQLModel but to Pydantic.
- [X] I already checked if it is not related to SQLModel but to SQLAlchemy.
Commit to Help
- [X] I commit to help with one of those options 👆
Example Code
created_at: datetime.datetime = datetime.datetime.now()
Description
I 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.
This is where it is in SSMS:

Operating System
Windows
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
3.9.12
Additional Context
No response
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:
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()")})
from sqlalchemy import text
Thanks a ton. This was exactly what I was looking for.