Given these classes and 1-to-N relationships, I get compile time error: ValueError: <class 'list'> has no matching SQLAlchemy type referring to the category.py field todos: list["Todo"], while the relation hero/team does work.
I also tried to replace the UUID type and use int in both classes, without success.
# hero.py (works)
class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
....
team_id: int | None = Field(default=None, foreign_key="team.id")
team: Team | None = Relationship(back_populates="heroes")
# team.py (works)
class Team(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
.....
heroes: list["Hero"] = Relationship(back_populates="team")
# todo.py (does not work)
class Todo(SQLModel, table=True):
id: UUID | None = Field(
default=uuid4(),
primary_key=True,
)
......
category_id: UUID | None = Field(default=None, foreign_key="category.id")
category: Category | None = Relationship(back_populates="todos")
# category.py (does not work => ValueError: <class 'list'>)
class Category(SQLModel, table=True):
id: UUID | None = Field(default=uuid4(), primary_key=True)
.....
todos: list["Todo"] = Relationship(back_populates="category")
Full error log:
import todo.models.category
File ".../todo/models/category.py", line 9, in <module>
class Category(SQLModel, table=True):
File ".../lib/python3.12/site-packages/sqlmodel/main.py", line 559, in __new__
col = get_column_from_field(v)
^^^^^^^^^^^^^^^^^^^^^^^^
File "../lib/python3.12/site-packages/sqlmodel/main.py", line 708, in get_column_from_field
sa_type = get_sqlalchemy_type(field)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "../lib/python3.12/site-packages/sqlmodel/main.py", line 697, in get_sqlalchemy_type
raise ValueError(f"{type_} has no matching SQLAlchemy type")
ValueError: <class 'list'> has no matching SQLAlchemy type
I encountered this issue when I tried to define field with list[str] type, like this:
class Example(SQLModel):
labels: list[str] | None = None
and solved it by making the field store data in JSON by using Column and JSON from sqlalchemy:
class Example(SQLModel):
labels: list[str] | None = Field(default=None, sa_column=Column(JSON))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With