Replies: 12 comments
-
Generally you can't do this kind of things with SQLModel without using SA api directly, so I'd just drop that want. |
Beta Was this translation helpful? Give feedback.
-
|
Coming from Tortoise ORM moving to SQLModel it would be great to have if the timezone would be saved without having to use SQLAlchemy directly. The project is new so I hope updates could be made soon. |
Beta Was this translation helpful? Give feedback.
-
|
New release has
so maybe this could be extended somehow to allow arguments for the sa Column type too. |
Beta Was this translation helpful? Give feedback.
-
|
That's how I sort this out now: from typing import Annotated
from datetime import datetime, timezone
import pytest
from pydantic import types as pydantic_types, ValidationError
from sqlmodel import Field, SQLModel, create_engine, Session, DateTime, Column
class DummySchema(SQLModel):
timestamp: pydantic_types.AwareDatetime = Field(sa_type=DateTime(timezone=True))
class DummyModel(DummySchema, table=True):
id: int | None = Field(default=None, primary_key=True)Indeed @antont , I believe adding That will throw an error: class DummySchema(SQLModel):
timestamp: pydantic_types.AwareDatetime = Field()while that works: Just considering all the as well as an updated Taking a step back, I believe the this kind of challenges quite common, and making type-mapping used in In the end one could: I can dig into contributing to this, yet I'd like to know if there any kind of interest for such a contrib'? |
Beta Was this translation helpful? Give feedback.
-
|
@Jufik yes there's interest - your solution works, if you can make the ergonomics more natural, this would be an improvement. Congruity with Pydantic directly supports the first three project objectives: ^ excerpted from: https://sqlmodel.tiangolo.com/ My 2¢ on the issue: using |
Beta Was this translation helpful? Give feedback.
-
|
I scoured the internet to find this post! For anyone else struggling with timezone aware datetime columns, I found this to be most effective.
OR
|
Beta Was this translation helpful? Give feedback.
-
|
I've been using these for a while now. Here the timezone is preserved and any latency is excluded since the value is generated by the db and not the app. If you prefer to add the field manually for every table: from sqlmodel import DateTime, text
...
my_date: datetime = Field(sa_column=Column(DateTime(timezone=True), server_default=text("NULL"), default=None))Your dates will be saved as If you prefer to extend them which is what I recommend: from sqlmodel import DateTime, func
from sqlalchemy.orm import declared_attr
class UpdatedAtMixin:
@declared_attr
def updated_at(self):
return Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=True)
class CreatedAtMixin:
@declared_attr
def created_at(self):
return Column(DateTime(timezone=True), server_default=func.now(), nullable=True)
class DeletedAtMixin:
@declared_attr
def deleted_at(self):
return Column(DateTime(timezone=True), server_default=text("NULL"), default=None, index=True)The need for Use it like so: class Account(UpdatedAtMixin, CreatedAtMixin, SQLModel, table=True):
...Personally, I created this instead to make things easier: class DTMixin(UpdatedAtMixin, CreatedAtMixin):
passthen use it as class Account(DTMixin, SQLModel, table=True):
... |
Beta Was this translation helpful? Give feedback.
-
I will try to implement your second implementation. But I've a question. How do you define the column name? I want to have a "date" column in one of my tables. I don't really care about the time, only the date itself. Thanks! |
Beta Was this translation helpful? Give feedback.
-
The column name would be the name of the method you choose. # Column name is `updated_at`
class UpdatedAtMixin:
@declared_attr
def updated_at(self):
return Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=True)
# Column name is `xyz`
class AbcMixin:
@declared_attr
def xyz(self):
return Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=True) |
Beta Was this translation helpful? Give feedback.
-
|
Thank you so much @enchance ! |
Beta Was this translation helpful? Give feedback.
-
|
I have a mixin here that adds creatd_at and updated_at: https://github.com/iloveitaly/activemodel/blob/master/activemodel/mixins/timestamps.py |
Beta Was this translation helpful? Give feedback.
-
|
Timezone-aware datetime without raw SQLAlchemy is doable! Option 1 - Field with sa_column: from sqlmodel import SQLModel, Field
from sqlalchemy import Column, DateTime
from datetime import datetime, timezone
class Event(SQLModel, table=True):
id: int = Field(default=None, primary_key=True)
created_at: datetime = Field(
sa_column=Column(DateTime(timezone=True)),
default_factory=lambda: datetime.now(timezone.utc)
)Option 2 - Custom type: from sqlmodel import SQLModel, Field
from datetime import datetime, timezone
from typing import Annotated
TZDateTime = Annotated[
datetime,
Field(sa_column=Column(DateTime(timezone=True)))
]
class Event(SQLModel, table=True):
created_at: TZDateTime = Field(default_factory=lambda: datetime.now(timezone.utc))Option 3 - Pydantic validator: from pydantic import field_validator
class Event(SQLModel, table=True):
created_at: datetime
@field_validator('created_at', mode='before')
def ensure_tz(cls, v):
if v.tzinfo is None:
return v.replace(tzinfo=timezone.utc)
return vThe key is using |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
I write my
created_atandupdated_atfields like this, however, this did not work, because of the time awareness,After checking Github, i found this solution:
It is written with mixing SQLModel stuff and the SALAlchemy, I know SQLModel is SQLAlchemy under the hood but this feels strange, cause i want to face SQLModel ONLY.
Is there any better way of handling this?
Let's say when SQLModel create tables, it will check the payding field
created_at, if it is timezone aware datetime then it will set it assa_column=sa.Column(sa.DateTime(timezone=True)so that we do not need to mix them both,Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.8
Python Version
3.10.2
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions