You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How to create a time Field for a model like django DateTimeField #370
when i change the Image_Save_Record instance which i created before and commit it to db, the update_time field value should be that system time current.
There are a few ways to do this, either via Pydantic or with SQLAlchemy.
SQLAlchemy is the way to go since implementing updated_at in it seems easier, but I'll leave the Pydantic approach here anyway since I wrote it first 😛
Having an automatic update time is a bit tougher... I think it should be possible with validators, but I can think of a few cases where the incorrect time can be set.
Doing this in SQLAlchemy is easy using server_default and on_update:
The above column definitions would mean that if time_created is None, then func.now() is the default, and if time_updated is changed, then its value will be overwritten with func.now().
Since you can directly use SQLAlchemy Columns in an SQLModel Field with the keyword argument sa_column, the above can just be copy/pasted into an SQLModel model:
Gave it a quick test and it seems to work correctly, when an instance of Model is first added and committed created_at is set to the current time and updated_at is None, then if foo is changed and the change is saved, updated_at is set to the time the save was done and created_at remains unchanged.
Reacted by Javier Soques, Sheldenburg and Graeme Holliday
@RobertRosca This is really helpful but there is an issue with created_at field. datetime on created_at is fixed for every resource creation. server_default assigns default data directly to the table when using alembic.
So when using the example code I showed with Alembic instead of SQLModel.metadata.create_all the created_at field always has the same value, as if the default value were set to a constant datetime?
I haven't tested it with Alembic, but their docs show that the server_default=func.now() should work to set the time to the current time for a timestamp column:
fromalembicimportopfromsqlalchemyimportColumn, TIMESTAMP, func# specify "DEFAULT NOW" along with the column addop.add_column('account',
Column('timestamp', TIMESTAMP, server_default=func.now())
)
I guess there could be some issue with interactions between Alembic, SQLAlchemy, and SQLModel causing the default to be a constant instead of the now function, but I haven't had time to look.
Since this should be supported by Alembic then if this isn't working correctly it's probably an issue in SQLModel, so I'd say open an issue here with some example code. I'll try and have a look some time this week as well, but maybe somebody else would be able to help before I can 😄
I don't understand... this definitely does not work for me.
I have a database containing some users, when I add the column created_at and execute alembic upgrade head I get this error:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) Cannot add a column with non-constant default
[SQL: ALTER TABLE users ADD COLUMN created_at DATETIME DEFAULT (CURRENT_TIMESTAMP)]
migration script:
defupgrade() ->None:
# ### commands auto generated by Alembic - please adjust! ###op.add_column('users', sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True))
# ### end Alembic commands ###defdowngrade() ->None:
# ### commands auto generated by Alembic - please adjust! ###op.drop_column('users', 'created_at')
# ### end Alembic commands ###
In env.py I added the argument render_as_batch=True to context.configure.
I autogenerated the migration.
I changed the upgrade function to add the created_at column with nullable=True, I updated the values with sa.func.now and then I batch_alter_table to make it nullable=False.
defupgrade() ->None:
# ### commands auto generated by Alembic - please adjust! ###print("Adding column created_at")
op.add_column("users", sa.Column("created_at", sa.DateTime(), nullable=True))
# Get the users.created_at columnuser=sa.sql.table(
"users",
sa.sql.column("created_at", sa.DateTime()),
)
# Update the users.created_at columnop.execute(user.update().values(created_at=sa.func.now()))
withop.batch_alter_table("users", schema=None) asbatch_op:
# Set the users.created_at column to not nullbatch_op.alter_column("created_at", nullable=False)
# ### end Alembic commands ###defdowngrade() ->None:
# ### commands auto generated by Alembic - please adjust! ###withop.batch_alter_table("users", schema=None) asbatch_op:
batch_op.drop_column("created_at")
This doesn't work if I factor out a field with sa_column attribute to another class and inherit from it, like:
classWithId(SQLModel):
""" Database row with ID field """id: UUID=Field(default_factory=lambda: ULID().to_uuid(), description='Row ULID', primary_key=True)
classTimedRow(SQLModel):
""" Database row with status times """created: datetime=Field(
default_factory=lambda: datetime.now(tz=config.timezone),
sa_column=Column(DateTime(timezone=True), server_default=text('CURRENT_TIMESTAMP'), nullable=False),
description='Time when row was created',
)
updated: datetime|None=Field(
sa_column=Column(DateTime(timezone=True)),
description='Time when row was last updated',
)
deleted: datetime|None=Field(
sa_column=Column(DateTime(timezone=True)),
description='Time when row was deleted',
)
classPractice(TimedRow, WithId, table=True):
name: str
If I have definitions like Practicein more than one module, I get:
sqlalchemy.exc.ArgumentError: Column object 'created' already assigned to Table '<tablename>'
on the second and following import of such a module.
Activity
RobertRosca commentedon Jun 29, 2022
There are a few ways to do this, either via Pydantic or with SQLAlchemy.
SQLAlchemy is the way to go since implementing
updated_atin it seems easier, but I'll leave the Pydantic approach here anyway since I wrote it first 😛With Pydantic default factories or validators
With Pydantic you could use default factories:
Another approach would be validators:
Having an automatic update time is a bit tougher... I think it should be possible with validators, but I can think of a few cases where the incorrect time can be set.
Doing this in SQLAlchemy is easy using
server_defaultandon_update:The above column definitions would mean that if
time_createdisNone, thenfunc.now()is the default, and iftime_updatedis changed, then its value will be overwritten withfunc.now().Since you can directly use SQLAlchemy Columns in an SQLModel Field with the keyword argument
sa_column, the above can just be copy/pasted into an SQLModel model:Gave it a quick test and it seems to work correctly, when an instance of
Modelis first added and committedcreated_atis set to the current time andupdated_atisNone, then iffoois changed and the change is saved,updated_atis set to the time the save was done andcreated_atremains unchanged.RobertRosca commentedon Jun 29, 2022
Here is my very rough example code:
Running it outputs:
So
created_atis constant, andupdate_atis 5 seconds aftercreated_atas expected given the 5 second sleep between creation and update.regainOWO commentedon Jun 30, 2022
@RobertRosca This example is very detailed! thanks a lot!
RobertRosca commentedon Jun 30, 2022
Thanks! Happy it helped 😄
I wrote up an explanation and created PR #372 to add this to the documentation, since it does come up pretty often.
RobertRosca commentedon Jul 1, 2022
I know #372 isn't merged yet, but if my example helped answer your question could you close this issue? Thanks 😄
Feel free to leave comments or suggestions on #372 as well if you have any!
veonim commentedon Oct 15, 2022
@RobertRosca This is really helpful but there is an issue with
created_atfield. datetime on created_at is fixed for every resource creation.server_defaultassigns default data directly to the table when using alembic.RobertRosca commentedon Oct 17, 2022
So when using the example code I showed with Alembic instead of
SQLModel.metadata.create_allthecreated_atfield always has the same value, as if the default value were set to a constant datetime?I haven't tested it with Alembic, but their docs show that the
server_default=func.now()should work to set the time to the current time for a timestamp column:I guess there could be some issue with interactions between Alembic, SQLAlchemy, and SQLModel causing the default to be a constant instead of the now function, but I haven't had time to look.
Since this should be supported by Alembic then if this isn't working correctly it's probably an issue in SQLModel, so I'd say open an issue here with some example code. I'll try and have a look some time this week as well, but maybe somebody else would be able to help before I can 😄
tiangolo commentedon Nov 8, 2022
Thanks a lot for the help here @RobertRosca ! 🍰
And thanks @regainOWO for coming back to close the issue. ☕
FilipeMarch commentedon Nov 8, 2022
I don't understand... this definitely does not work for me.
I have a database containing some users, when I add the column
created_atand executealembic upgrade headI get this error:migration script:
I just added this line to
Userstable:FilipeMarch commentedon Nov 8, 2022
I figured out this works:
I added these lines to
Usertable:In
env.pyI added the argumentrender_as_batch=Truetocontext.configure.I autogenerated the migration.
I changed the
upgradefunction to add thecreated_atcolumn with nullable=True, I updated the values withsa.func.nowand then Ibatch_alter_tableto make it nullable=False.FilipeMarch commentedon Nov 9, 2022
I also implemented
updated_atfield here with the following:Add this to the your
SQLModel:Alembic migration:
Or in case you are using batch operation:
jwezel commentedon Mar 17, 2025
This doesn't work if I factor out a field with
sa_columnattribute to another class and inherit from it, like:If I have definitions like
Practicein more than one module, I get:on the second and following import of such a module.