问题
当尝试使用 sqlmodel 运行 Python 脚本时,你看到以下错误消息:
File "/home/uli/Nextcloud/Experimental/InventreeLCSC/model/LCSC.py", line 32, in <module>
class Offer(SQLModel, table=True):
File "/home/uli/.local/lib/python3.12/site-packages/sqlmodel/main.py", line 620, in __init__
ins = inspect(rel_info.link_model)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/uli/.local/lib/python3.12/site-packages/sqlalchemy/inspection.py", line 147, in inspect
raise exc.NoInspectionAvailable(
sqlalchemy.exc.NoInspectionAvailable: No inspection system is available for object of type <class 'str'>
解决方案
这是因为你在 Relationship 字段中为 link_model 参数使用了字符串。
之前:
bad_relationship_example.py
class ProductOfferLink(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
product_id: int = Field(foreign_key="product.id")
offer_id: int = Field(foreign_key="offer.id")
class Product(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
# ...
offers: List[Offer] = Relationship(
back_populates="products",
link_model="ProductOfferLink" # <-- ERROR
)
之后:
fix_relationship_example.py
class ProductOfferLink(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
product_id: int = Field(foreign_key="product.id")
offer_id: int = Field(foreign_key="offer.id")
class Product(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
# ...
offers: List[Offer] = Relationship(
back_populates="products",
link_model=ProductOfferLink # <-- FIXED
)
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow