SQLModel - Error when initializing mapper expression failed to locate a name

23 Views Asked by At

I'm using SQLModel as my ORM, but I'm having an issue when try to instante tables.

File structure

--| orm
--|--| __init__.py
--|--| base_table.py
--|--| tables
--|--|--| __init__.py
--|--|--| master_product.py
--|--|--| codes
--|--|--|-- __init__.py
--|--|--|-- season_code.py

Code

File base_table.py

from __future__ import annotations
from abc import ABC
from datetime import datetime
from sqlmodel import Field, SQLModel

class BaseTable(SQLModel, ABC, table=False):
    creation_date: datetime = Field(default_factory=datetime.now)

File tables.codes.season_code.py

from __future__ import annotations
from ...base_table import BaseTable
from sqlmodel import Field

class SeasonCode(BaseTable, table=True):
    __tablename__ = 'season_code'

    code: str = Field(max_length=3, primary_key=True)

File tables.master_product.py

from __future__ import annotations
from ..base_table import BaseTable
from sqlmodel import Field, Relationship
from .codes.season_code import SeasonCode

class MasterProduct(BaseTable, table=True):
    __tablename__ = 'master_product'
    identifier: str = Field(max_length=17, primary_key=True)
    season_code: str | None = Field(max_length=3, default=None, foreign_key="season_code.code")
    season: SeasonCode | None = Relationship()

File __init__.py

from __future__ import annotations
from .tables.codes.season_code import SeasonCode
from .tables.master_product import MasterProduct
__all__ = [
    'SeasonCode',
    'MasterProduct',
]

Error

import SeasonCode
SeasonCode(code='aaa')
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper[MasterProduct(master_product)], expression 'SeasonCode | None' failed to locate a name ('SeasonCode | None'). If this is a class name, consider adding this relationship() to the <class 'orm.tables.master_product.MasterProduct'> class after both dependent classes have been defined.

I discovered that the problem disappears if I set season: SeasonCode = Relationship() (without | None) but I don't understand why

0

There are 0 best solutions below