-
First Check
Commit to Help
Example Codefrom pathlib import Path
from typing import Optional
import pytest
from sqlmodel import VARCHAR, Column, Field, Session, SQLModel, create_engine
class MyFile(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
path: Path = Field(sa_column=Column(VARCHAR))
@pytest.fixture
def session() -> Session:
engine = create_engine(
'sqlite://', connect_args={'check_same_thread': False})
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
yield session
def test_myfile(session: Session, tmp_path: Path):
session.add(MyFile(path=tmp_path / 'test.txt'))
session.commit() Description
Operating SystemLinux Operating System DetailsUbuntu 22.04. SQLModel Version0.0.6 Python Version3.10 Additional ContextLogs from the test case:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I don't know about this, but would not be surprising as a Path is not a string, but has also attributes like parents. It can be made from a string though, so that would at least work with the varchar in db. Searched for the docs and happened to see this, might be a different thing though as is not with db code there. fastapi/fastapi#563 Ah the fix there is to make it jsonable: Other folks here use json db fields for some things I think, we haven't so far but just have strings and ints and such in the db like usually. Am using strings for paths in the sqlmodel db models. Well or don't have paths but just filenames and paths come from runtime logic. |
Beta Was this translation helpful? Give feedback.
-
Any update on this ? I think I can live with modeling Can I somehow add the FastAPI fix to my code locally ? |
Beta Was this translation helpful? Give feedback.
-
You maybe could use a SQLAlchemy Custom Type to convert from pathlib import Path
from sqlalchemy.types import TypeDecorator, String
class PathType(TypeDecorator):
impl = String
def process_bind_param(self, value, dialect):
if isinstance(value, Path):
return str(value)
return value
def process_result_value(self, value, dialect):
if value is not None:
return Path(value)
return value And use it like this: class MyFile(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
path: Path = Field(sa_column=Column(PathType)) Stumbled on this thread by accident while researching a similar issue. Hope it helps! |
Beta Was this translation helpful? Give feedback.
You maybe could use a SQLAlchemy Custom Type to convert
Path
to / from string: