sqlmodel icon indicating copy to clipboard operation
sqlmodel copied to clipboard

Am I able to set a SQL field default value or binding?

Open configureng opened this issue 3 years ago • 2 comments

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: image

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.9.12

Additional Context

No response

configureng avatar Aug 19 '22 00:08 configureng

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()")})

meirdev avatar Aug 19 '22 07:08 meirdev

from sqlalchemy import text

Thanks a ton. This was exactly what I was looking for.

configureng avatar Aug 19 '22 13:08 configureng