FastAPI, SQLModel - Pydantic not serializing datetime

156 views Asked by At

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.

1

There are 1 answers

0
Octavio del Ser On BEST ANSWER

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)