[Python] How to avoid a NameError in SQLAlchemy when using an ORM for a MySQL database?

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    How do I avoid having a NameError when the class definitions for each table is in a different file when using SQLAlchemy to manage a MySQL database?

    For example:

    # in dish.py

    class Dish(Base):
    __tablename__ = "dishes"
    ID: Mapped[int] = mapped_column(Integer, primary_key=True)
    name: Mapped[str] = mapped_column(String(255))

    composition: Mapped[List["Recipe"]] = relationship(
    back_populates="dish",
    foreign_keys="Recipe.ID_dish")

    def get_ingredient_list(self):
    return composition

    # in ingredient.py

    class Ingredient(Base):
    __tablename__ = "ingredients"
    ID: Mapped[int] = mapped_column(Integer, primary_key=True)
    name: Mapped[str] = mapped_column(String(255))

    in_dishes: Mapped[List["Recipe"]] = relationship(
    back_populates="ingredient",
    foreign_keys="Recipe.ID_ingredient")

    # in recipe.py (the linking table)

    class Recipe(Base):
    __tablename__ = "recipe"
    ID_dish: Mapped[int] = mapped_column(Integer, ForeignKey("dishes.ID"), primary_key=True)
    ID_ingredient: Mapped[int] = mapped_column(Integer, ForeignKey("ingredients.ID"), primary_key=True)
    amount: Mapped[float] = mapped_column(DECIMAL(5,2))

    dish: Mapped["Dish"] = relationship(
    back_populates="composition",
    foreign_keys=[ID_dish])

    ingredient: Mapped["Ingredient"] = relationship(
    back_populates="in_dishes",
    foreign_keys=[ID_ingredient])

    # in the main file

    from dish import Dish
    from ingredient import Ingredient
    from recipe import Recipe

    ing_list = some_dish.get_ingredient_list()
    print(ing_list)



    My problem is that this returns a NameError where the classes are not defined. I guess this happens because the related classes are not imported in the modules.

    How can I solve this problem?

    Continue reading...

Compartilhe esta Página