sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Event->event, expression 'Tag' failed to locate a name ('Tag')

Question:

I am trying to use ORM with SQLAlchemy in Python. My current solution fails and throws an exception right in the moment the ORM is first used. I receive the following exception:

sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Event->event, expression 'Tag' failed to locate a name ('Tag'). If this is a class name, consider adding this relationship() to the <class 'backend.source.database.event.Event'> class after both dependent classes have been defined.

My classes are defined like in the offical SQLAlchemy-Documentation (https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html#many-to-many), which is why I am kinda confused about that error.

association = Table('event_to_tag', declarative_base().metadata,
                    Column('event_id', Integer, ForeignKey('event.id'), primary_key=True),
                    Column('tag_id', Integer, ForeignKey('tag.id'), primary_key=True))


class Event(declarative_base()):
    __tablename__ = "event"

    id = Column(Integer, primary_key=True)
    title = Column(String(255))
    location = Column(String(255))
    organizer_id = Column(Integer, ForeignKey(Organizer.id))
    start = Column(DateTime)
    end = Column(DateTime)
    lang = Column(String(255))
    costs = Column(DECIMAL)
    registration = Column(TINYINT)
    url = Column(String(255))
    description = Column(Text)

    tags = relationship("Tag", secondary=association, back_populates="events")


class Tag(declarative_base()):
    __tablename__ = "tag"

    id = Column(Integer, primary_key=True)
    name = Column(String(255))

    events = relationship("Event", secondary=association, back_populates="tags")

Thank you, greetings

Asked By: longroad

||

Answers:

I think you need to define a Base = declarative_base(), need to use in your models and associations.

from sqlalchemy import Column, Integer, ForeignKey, String, DECIMAL, Text, DateTime, Table, create_engine
    from sqlalchemy.dialects.mssql import TINYINT
    from sqlalchemy.dialects.postgresql import UUID
    from sqlalchemy.orm import declarative_base, relationship, scoped_session, sessionmaker
    
Base = declarative_base()

association = Table('event_to_tag',
                    Base.metadata,
                    Column('event_id', Integer, ForeignKey('events.id'), primary_key=True),
                    Column('tag_id', Integer, ForeignKey('tags.id'), primary_key=True))


class Event(Base):
    __tablename__ = "events"
    id = Column(Integer, primary_key=True)
    title = Column(String(255))
    location = Column(String(255))
    # organizer_id = Column(Integer, ForeignKey(Organizer.id))
    start = Column(DateTime)
    end = Column(DateTime)
    lang = Column(String(255))
    costs = Column(DECIMAL)
    registration = Column(UUID)
    url = Column(String(255))
    description = Column(Text)

    tags = relationship("Tag", secondary=association, back_populates="events")


class Tag(Base):
    __tablename__ = "tags"

    id = Column(Integer, primary_key=True)
    name = Column(String(255))

    events = relationship("Event", secondary=association, back_populates="tags")


class CreateEngine:

    def __init__(self):
        self.connection_string = "postgresql+psycopg2://<user_name>:<password>@127.0.0.1/<table_name>"
        self.engine = create_engine(self.connection_string)

    def create_table(self):
        return Base.metadata.create_all(self.engine)

    def create_session(self):
        session_factory = sessionmaker(bind=self.engine)
        Session = scoped_session(session_factory)
        with Session() as session:
            pass


if __name__ == "__main__":
    CreateEngine().create_table()
Answered By: Şahin Murat Oğur
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.