Type | None not working when Type is a class #923
-
First Check
Commit to Help
Example Codefrom typing import TYPE_CHECKING, Optional
from sqlmodel import Field, Relationship, SQLModel
if TYPE_CHECKING:
from .team_model import Team
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: "Team" | None = Relationship(back_populates="heroes") Description
team: "Team" | None = Relationship(back_populates="heroes")
~~~~~~~^~~~~~
TypeError: unsupported operand type(s) for |: 'str' and 'NoneType'
Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.18 Python VersionPython 3.10.13 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Answered by
joachimhuet
May 5, 2024
Replies: 2 comments 5 replies
-
I had the same issue, and I was forced to use |
Beta Was this translation helpful? Give feedback.
1 reply
-
Well you could use Or you can Hope this helps |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mmh in fact I don't think it's a bug. It seems normal to not be able to use an object that has not yet been defined. By doing this
if TYPE_CHECKING: ...
we just import during type checking, meaning that we do not have access to the object yet. And probably, inRelationship
there is a use of that.And in fact for the example I gave using pure pydantic if you import Hero and instantiate Hero before importing Team you should have an error. This is also the case with the example from the documentation using
Optional[Team]
if you only import hero and try to instantiate a hero without giving it a team you will have the sameKeyError: 'Team'
. And having to keep in mind that a Team must be import…