Comments (13)
This is how I use updated_at
:
from sqlmodel import SQLModel, Column, Field
from sqlalchemy import DateTime, func
from typing import Optional
import datetime
class Article(SQLModel, table=True):
created_at: datetime.datetime = Field(
default_factory=datetime.datetime.utcnow,
)
updated_at: Optional[datetime.datetime] = Field(
sa_column=Column(DateTime(), onupdate=func.now())
)
Some people might regard update_at as when a new version of the record was created rather than when the record is updated later on
Personally I believe this does not make much sense.
- When the record is created at 5PM, it was created_at 5PM.
- When the record is updated at 7PM, it was updated_at 7PM.
from sqlmodel.
Just going to throw this out there - created at / updated at / soft deleted at are really common patterns and there might be a bit of value to just make them first class features
from sqlmodel.
This is the cleanest way I have found to do it
core_models.py
class SimpleIDModel(BaseModel):
id: int
class UUIDIDModel(BaseModel):
id: UUID = Field(default_factory=uuid4)
class TimestampModel(BaseModel):
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: Optional[datetime]
class EventTimestamp(BaseModel):
occured_at: Optional[datetime]
consuming.py
class Service(SimpleIDModel, TimestampModel, table=True):
name: str = Field(nullable=False)
description: str = Field(nullable=False)
I think having opinionated timestamping might not work.
Some people might regard update_at as when a new version of the record was created rather than when the record is updated later on
from sqlmodel.
I do the same as @antont but without the lambda
from sqlmodel import SQLModel, Field
import datetime
class Article(SQLModel, table=True):
created_at: datetime.datetime = Field(
default_factory=datetime.datetime.utcnow,
)
from sqlmodel.
It's common to delegate generating timestamps to the database rather than generating them in Python. Much like @FilipeMarch is showing in the
update_at
column.In that case you would set the server_default attribute on the column. In the case of sqlalchemy it would look like this:
time = db.Column(db.Time, server_default=sqlalchemy.func.now())
I agree it's worth having a firstclass feature for this.
I agree generating timestamp should be dealt with by the database. In this case, I currently use this
class Game(GameBase, table=True):
created_at: datetime = Field(
sa_column_kwargs={
"server_default": text("CURRENT_TIMESTAMP"),
}
)
The advantage of this is I don’t need to refer to an actual sa_column, and using CURRENT_TIMESTAMP adheres to ansi sql standards
from sqlmodel.
lol I don't know why we had the useless lambda, i guess some mindless copy-paste, thanks, will get to clean those up.
from sqlmodel.
We've been doing it like this
from datetime import datetime
from sqlmodel import SQLModel, Field
(...)
created_at: datetime = Field(default_factory=lambda: datetime.now())
from sqlmodel.
It's common to delegate generating timestamps to the database rather than generating them in Python. Much like @FilipeMarch is showing in the update_at
column.
In that case you would set the server_default attribute on the column. In the case of sqlalchemy it would look like this:
time = db.Column(db.Time, server_default=sqlalchemy.func.now())
I agree it's worth having a firstclass feature for this.
from sqlmodel.
Yes, I think a mixin might work. I do think it's worth having a discussion how created at / updated at / deleted at would fit with created by / updated by / deleted by (so user IDs, which may be an integer or string type) as well as versioned entities (does created / updated just get replaced with "updated", and "created" is implicit with version 1?)
from sqlmodel.
The advantage of this is I don’t need to refer to an actual sa_column, and using CURRENT_TIMESTAMP adheres to ansi sql standards
wow, amazing, this is works pretty good with alembic's --autogenerate
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"users",
sa.Column(
"created_at",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
),
)
from sqlmodel.
Just going to throw this out there - created at / updated at / soft deleted at are really common patterns and there might be a bit of value to just make them first class features
How would you do it? Maybe a mixin in some library module, that one can use to add features to base SQLModel?
from sqlmodel.
Is the solution in #594 (comment) the answer? Can the issue be closed?
from sqlmodel.
This can be closed.
from sqlmodel.
Related Issues (20)
- Data Integrity: Raise error on attempt to delete an object required via a Relationship HOT 8
- [Querying] negating `Model.boolean` in `where()` HOT 2
- [M2M] Query dependent incl. `link_model` fields HOT 3
- Could not refresh instance HOT 9
- SQLModel doesn't recognize Relationship between models HOT 1
- Get select with options (selectinload) using response schema HOT 2
- Dose there any better way to write timezone aware datetime field without using the SQLAlchemy ? HOT 3
- Obtaining `TypeError: Cannot pickle 'module' object` on models with many-to-many relationships HOT 2
- Order of columns in the table created does not have 'id' first, despite the order in the SQLModel. Looks like it's prioritising fields with sa_column HOT 3
- Erro ao executar uvicorn.run(...) HOT 1
- Many to many relationship between a table and itself HOT 6
- Add documentation about how to use the async tools (session, etc) HOT 6
- async relationship bug HOT 10
- 🚀 Roadmap HOT 28
- Internal link failed at create-db-and-table.md
- Field cannot autocompletion when its a SQLModel HOT 7
- Add an overload to the `exec` method with `_Executable` statement for update and delete statements HOT 1
- How to define table prefix name
- docs/contributing.md outdated using poetry HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from sqlmodel.