question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to create a time Field for a model like django DateTimeField

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google “How to X in SQLModel” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from datetime import datetime
from typing import Optional
from sqlmodel import Field, SQLModel, DateTime


class Image_Save_Record(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)

    camera_ip: str
    camera_channel: int
    file_path: str
    file_name: str
    create_time: DateTime 
    update_time: DateTime

Description

when i create a Image_Save_Record instance and commit it to db, the create_time field value should be that system time current.

# django version
create_time = models.DateTimeField(auto_now_add=True)

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.

# django version
update_time = models.DateTimeField(auto_now=True)

Is there sqlmodel have option to do the same like this?

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.7.9

Additional Context

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:11 (6 by maintainers)

github_iconTop GitHub Comments

5reactions
RobertRoscacommented, Jun 29, 2022

Here is my very rough example code:

import time
from datetime import datetime
from typing import Optional

from sqlalchemy import Column, DateTime, func
from sqlmodel import Field, Session, SQLModel, create_engine, select


class Model(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)

    foo: Optional[str]

    created_at: Optional[datetime] = Field(
        sa_column=Column(DateTime(timezone=True), server_default=func.now())
    )

    updated_at: Optional[datetime] = Field(
        sa_column=Column(DateTime(timezone=True), onupdate=func.now())
    )


sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"

engine = create_engine(sqlite_url)


def create_db_and_tables():
    SQLModel.metadata.create_all(engine)


def create_entry():
    with Session(engine) as session:
        m = Model()

        print(f"created {m=}")

        session.add(m)
        session.commit()
        session.refresh(m)

        print(f"added and refreshed {m=}")


def update_entry():
    with Session(engine) as session:
        s = select(Model)
        m = session.exec(s).first()

        print(f"\nfound {m=}")

        m.foo = "bar"

        print(f"modified {m=}")

        session.add(m)
        session.commit()
        session.refresh(m)

        print(f"refreshed {m=}")


def main():
    create_db_and_tables()
    create_entry()
    time.sleep(5)
    update_entry()


if __name__ == "__main__":
    main()

Running it outputs:

created m=Model(id=None, foo=None, created_at=None, updated_at=None)
added and refreshed m=Model(foo=None, created_at=datetime.datetime(2022, 6, 29, 8, 14, 53), updated_at=None, id=1)

found m=Model(foo=None, created_at=datetime.datetime(2022, 6, 29, 8, 14, 53), updated_at=None, id=1)
modified m=Model(foo='bar', created_at=datetime.datetime(2022, 6, 29, 8, 14, 53), updated_at=None, id=1)
refreshed m=Model(foo='bar', created_at=datetime.datetime(2022, 6, 29, 8, 14, 53), updated_at=datetime.datetime(2022, 6, 29, 8, 14, 58), id=1)

So created_at is constant, and update_at is 5 seconds after created_at as expected given the 5 second sleep between creation and update.

0reactions
FilipeMarchcommented, Nov 9, 2022

I also implemented updated_at field here with the following: Add this to the your SQLModel:

updated_at: Optional[datetime.datetime] = Field(
        sa_column=Column(DateTime(), onupdate=func.now())
    )

Alembic migration:

def upgrade() -> None:
    op.add_column("users", sa.Column("updated_at", sa.DateTime(), nullable=True))

def downgrade() -> None:
    op.drop_column("users", "updated_at")

Or in case you are using batch operation:

def upgrade() -> None:
    with op.batch_alter_table('users', schema=None) as batch_op:
        batch_op.add_column(sa.Column('updated_at', sa.DateTime(), nullable=True))

def downgrade() -> None:
    with op.batch_alter_table('users', schema=None) as batch_op:
        batch_op.drop_column('updated_at')
Read more comments on GitHub >

github_iconTop Results From Across the Web

DateTimeField - Django Models - GeeksforGeeks
DateTimeField – Django Models ... DateTimeField is a date and time field which stores date, represented in Python by a datetime.datetime instance.
Read more >
Creating a Django DateTimeField - eduCBA
Create a Django DateTimeField. 1. Changes in Models.py file: As mentioned in the syntax section the Date Time field needs to be declared...
Read more >
Django Tips #4 Automatic DateTime Fields
Both Django's DateTimeField and DateField have two very useful arguments for automatically managing date and time.If you want keep track on ...
Read more >
Automatic DateTime Fields in Django | Django Tips#4
Both Django's DateTimeField and DateField have two very useful arguments for automatically managing date and time.
Read more >
Automatic creation date for Django model form objects
You can use the auto_now and auto_now_add options for updated_at and created_at respectively. class MyModel(models.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found