-
First Check
Commit to Help
Example Codequery = select(User).options(selectinload(User.team)).offset(offset).limit(limit) DescriptionHello, I'm running a one-to-many, Team to User classic relationship. Table User declares field class User(SQLModel, table=True)
...
team_id: str | None = Field(
default=None,
foreign_key="team.id",
}
team: Team | None = Relationship(back_populates="users") All is good, except a MyPy typing error on error: Argument 1 to "selectinload" has incompatible type "Team | None";
expected "Literal['*'] | QueryableAttribute[Any]" [arg-type] When using: from sqlalchemy.orm import selectinload
query = select(User).options(selectinload(User.team)).offset(offset).limit(limit) Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.16 Python VersionPython 3.11.7 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Have you solved it?, cause i get the same exception |
Beta Was this translation helpful? Give feedback.
-
Hey 🙂 As a note for the future, please try to provide a minimal, reproducible example. Following the Discussion Guidelines is important to help us help you. This is my attempt at recreating your situation: from sqlmodel import Field, Relationship, SQLModel, create_engine, Session, select
from sqlalchemy.orm import selectinload
class Team(SQLModel, table=True):
id: int = Field(primary_key=True)
name: str = Field()
users: list["User"] = Relationship(back_populates="team")
class User(SQLModel, table=True):
name: str = Field(primary_key=True)
team_id: str | None = Field(
default=None,
foreign_key="team.id",
)
team: Team | None = Relationship(back_populates="users")
engine = create_engine("sqlite:///example.db")
SQLModel.metadata.create_all(engine)
team1 = Team(name="Team Rocket")
user1 = User(name="Jessie", team=team1)
user2 = User(name="James", team=team1)
with Session(engine) as session:
session.add(team1)
session.add(user1)
session.commit()
query = select(User).options(selectinload(User.team)).offset(1).limit(1)
users = session.exec(query)
print([r for r in users]) However, this version runs as-is without any issues (I used SQLModel 0.0.16 and SQLAlchemy 2.0.29, but I'm using Python 3.12, though I doubt that's the cause). If your use-case is different, feel free to modify this example to better illustrate it 🙂 Maybe you can show us yours as well @AlPashy |
Beta Was this translation helpful? Give feedback.
You're both right, I apologize. For some reason mypy wasn't picking up that error on my side.
In the meantime, I think I found the issue:
By changing
team: Team | None
toteam: Mapped[Team | None]
(note thatMapped
is imported fromsqlalchemy.orm
), the error seems to disappear, while the example still works as intended. However, I'm not sure if this has any side effects, namely with Pydantic (assuming you're using FastAPI), so you might want to check that, just to be sure.