鉴于这些类和 1 对 N 关系,我收到编译时错误:
ValueError: <class 'list'> has no matching SQLAlchemy type
指的是 category.py
字段 todos: list["Todo"]
,而关系 hero/team
确实有效。
我还尝试在两个类中替换
UUID
类型并使用 int
,但没有成功。
# 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")
完整错误日志:
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
我检查了 FastAPI docs 并发现了一条注释:
Notice that the relationship attributes, the ones with Relationship(), are only in the table models, as those are the ones that are handled by SQLModel with SQLAlchemy and that can have the automatic fetching of data from the database when we access them.
class TeamBase(SQLModel):
name: str = Field(index=True)
headquarters: str
class Team(TeamBase, table=True):
id: int | None = Field(default=None, primary_key=True)
heroes: list["Hero"] = Relationship(back_populates="team")
class HeroBase(SQLModel):
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
class Hero(HeroBase, table=True):
id: int | None = Field(default=None, primary_key=True)
team: Team | None = Relationship(back_populates="heroes")
我认为你应该尝试将你的模型分成两个类:用于数据库字段的 SQLModel 和用于关系的表模型,然后再次检查。希望你能解决这个问题!