How to fix sqlmodel / sqlalchemy NoInspectionAvailable: No inspection system is available for object of type <class 'str'>

Problem

When trying to run your Python script using sqlmodel, you see the following error message:

  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'>

Solution

This is because you are using a string for the link_model parameter in a Relationship field.

Before:

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
    )

After:

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
    )