pythonfastapipydanticsqlmodel

FastAPI, SQLModel - Pydantic not serializing datetime


My understanding is that SQLModel uses pydantic BaseModel (checked the _mro_. Why is it that the bellow fails the type comparison. (err provided).

class SomeModel(SQLModel,table=True):
    timestamp: datetime
    id: UUID = Field(default_factory=lambda: str(uuid4()), primary_key=True)

def test_some_model():
    m=SomeModel(**{'timestamp':datetime.utcnow().isoformat()})
    assert type(m.timestamp)==datetime

E AssertionError: assert <class 'str'> == datetime

FastAPI/SQLModel experts explain yourselves :D .

Note - I tried using Field with default factories etc... as well.


Solution

  • Adding validate_assignment fixes the issue.

    Picked this solution up from https://github.com/tiangolo/sqlmodel/issues/52 after more than a couple days of breaking my head. Hopefully this helps other poor souls.

       class SomeModel(SQLModel,table=True):
            class Config:
                validate_assignment = True
            timestamp: datetime
            age:int
            id: UUID = Field(default_factory=lambda: str(uuid4()), primary_key=True)