Wie man sqlmodel / sqlalchemy NoInspectionAvailable behebt: No inspection system is available for object of type <class 'str'>

English Deutsch

Problem

Beim Versuch, Ihr Python-Skript mit sqlmodel auszuführen, sehen Sie die folgende Fehlermeldung:

sqlmodel_error_trace.sh
  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'>

Lösung

Dies liegt daran, dass Sie einen String für den link_model-Parameter in einem Relationship-Feld verwenden.

Vorher:

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
    )

Nachher:

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
    )

Check out similar posts by category: SQLModel, Python, Database