GithubHelp home page GithubHelp logo

Comments (13)

JamesHutchison avatar JamesHutchison commented on May 27, 2024 10

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.

FilipeMarch avatar FilipeMarch commented on May 27, 2024 9

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.

FilipeMarch avatar FilipeMarch commented on May 27, 2024 8

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.

firecube-oss avatar firecube-oss commented on May 27, 2024 8

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.

PookieBuns avatar PookieBuns commented on May 27, 2024 6

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.

antont avatar antont commented on May 27, 2024 5

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.

antont avatar antont commented on May 27, 2024 4

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.

speetpeet avatar speetpeet commented on May 27, 2024 4

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.

JamesHutchison avatar JamesHutchison commented on May 27, 2024 2

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.

mj2068 avatar mj2068 commented on May 27, 2024 2

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.

antont avatar antont commented on May 27, 2024

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.

rafalkrupinski avatar rafalkrupinski commented on May 27, 2024

Is the solution in #594 (comment) the answer? Can the issue be closed?

from sqlmodel.

danielqba avatar danielqba commented on May 27, 2024

This can be closed.

from sqlmodel.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.