In some cases you may need more control over the columns generated by SQLModel, this can be done by using the sa_column, sa_column_args, and sa_column_kwargs arguments when creating the Field object.
There are many use cases for this, but ones where this is particularity useful is when you want more advanced defaults for values than what is easy to implement with Pydantic, such created_at or update_at timestamps for rows.
Two ways of implementing created_at timestamps with Pydantic are default factories and validators, however there's no straightforward way to have an update_at timestamp.
The SQLAlchemy docs describe how created_at timestamps can be automatically set with either default or server-default functions, by using sa_column=Column(...) as described in the SQLAlchemy documentation we can achieve the same behaviour:
{* ./docs_src/advanced/sa_column/tutorial001.py ln[9:21] hl[16,20] *}
Above we are saying that the registered_at column should have a server_default value of func.now() (see full code for imports), which means that if there is no provided value then the current time will be the recorded value for that row.
As there is a value there now, then it will not be changed automatically in the future.
The updated_at column has an onupdate value of func.now(), this means that each time an UPDATE is performed, the function will be executed, meaning that the timestamp changes whenever a change is made to the row.
/// warning
The difference between client-side python functions, server-side ddl expressions, and server-side implicit defaults is important in some situations but too in-depth to go into here. Check the SQL and SQLAlchemy docs for more information.
///
Implementing these timestamps on the DB side with SQLAlchemy works very well as the database itself is what will create and update the fields whenever a relevant database interaction occurs.
It's possible to achieve similar behaviour with Pydantic, for the created_at timestamp by using a Pydantic Field with a default_factory:
from datetime import datetime
from pydantic import BaseModel, Field
class Model(BaseModel):
created_at: datetime = Field(default_factory=datetime.utcnow)
m1 = Model()
m2 = Model()
print(f'{m1.created_at} != {m2.created_at}')
#> 2022-05-19 10:49:22.053624 != 2022-05-19 10:49:22.053641Another approach is to use a Pydantic validator:
from datetime import datetime
from pydantic import BaseModel, validator
class Model(BaseModel):
created_at: datetime = None
@validator('ts', pre=True, always=True)
def set_created_at_now(cls, v):
return v or datetime.now()Both of these approaches come with the major caveat that default fields are set during the Pydantic model instantiation, as opposed to during interactions with the database, instead of the SQLModel approach which sets it with server_default which means that the timestamp will be exactly when the row is created in the database.
The real issue starts when looking at the updated_at timestamp - SQLAlchemy has the onupdate default which runs a function when the row is updated in the database, but there is no easy way to do this in Pydantic as it has no concept of 'about to be saved'.
So the pure Pydantic approach would require some additional logic to always change the updated_at timestamp before doing a write to the database, which adds some more complexity to the code and does not have benefits over the SQLAlchemy approach.