sqlalchemy InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers

Viewed 1403

I have the following tables using SQLAlchemy

#Sistema de escuelas por Jenifer
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Sequence, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

###############Creación de la base de datos #########################################
engine=create_engine('sqlite:///:memory:')
Base=declarative_base(engine)

class Estudiante(Base):
    __tablename__="alumno"   
    id=Column(Integer,Sequence('alumno_seq_id'),primary_key=True)
    cedula_identidad=Column(String)
    nombre_alumno=Column(String)
    apellido_alumno=Column(String)
    curso_idAlumno=Column(Integer,ForeignKey('curso.id'))
    
    cursos=relationship("Curso",back_populates='estudiantes')
    #cursos=relationship("Curso",back_populates='alumno')
    def __repr__(self):
        return'{}{}'.format(self.nombre_alumno, self.apellido_alumno)

class Curso(Base):
    __tablename__='curso'
    id=Column(Integer, Sequence('curso_seq_id'),primary_key=True)
    nombre_curso=Column(String)
        
    estudiantes=relationship("Estudiante",back_populates='curso')
    hora_curso=relationship("Horarios",back_populates='curso_hora')
    def __repr__(self):
        return'{}'.format(self.nombre_curso)

class Horarios(Base):
    __tablename__='horario'
    id=Column(Integer, Sequence('horario_seq_id'),primary_key=True)
    dia=Column(String)
    hora_inicio=Column(String)
    hora_fin=Column(String)
    profesor_id=Column(Integer,ForeignKey('profesor.id'))
    curso_id=Column(Integer,ForeignKey('curso.id'))
    
    curso_hora=relationship("Curso",back_populates='hora_curso')
    curso_profe=relationship("Profesor",back_populates='profe_curso')

    def __repr__(self):
        return'{}{}{}'.format(self.dia,self.hora_inicio, self.hora_fin,\
        self.cedula_identidad)

class Profesor(Base):
    __tablename__='profesor'
    id=Column(Integer, Sequence('profesor_seq_id'),primary_key=True)
    cedula_identidad=Column(String)    
    nombre_profesor=Column(String)
    apellido_profesor=Column(String)
    
    profe_curso=relationship("Horarios",back_populates='curso_profe')
    def __repr__(self):
        return'{}{}{}'.format(self.nombre_profesor, self.apellido_profesor,
        self.cedula_identidad)


Profesor.__table__
Estudiante.__table__
Curso.__table__
Horarios.__table__
Base.metadata.create_all(engine)

And the following function to preload data:

def precargarDatos(ses):
###############ESTUDINTES##################################################
    alumno1=Estudiante(nombre_alumno='Raton', apellido_alumno='Perez',
    cedula_identidad='1234567-8')
    alumno2=Estudiante(nombre_alumno='Hugo', apellido_alumno='Donald',\
    cedula_identidad='abcdef123')
    alumno3=Estudiante(nombre_alumno='Paco', apellido_alumno='Donald',\
    cedula_identidad='abcdef124')
    alumno4=Estudiante(nombre_alumno='Luis', apellido_alumno='Donald',\
    cedula_identidad='abcdef125')
    ses.add(alumno1)
    ses.add(alumno2)
    ses.add(alumno3)
    ses.add(alumno4)

The problem is that when I try to run this it gives me the following error:

InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Estudiante->alumno'. Original exception was: Mapper 'mapped class Curso->curso' has no property 'alumno'

This error rises when I try to assign alumno1 using the class Estudiante. I've seen similar posts but I can't figure out what to change in my code, if the problem is the function or the definition of the tables. If enyone can help me I will appreciate it

2 Answers

Thanks to @snakecharmberb I noticed the errors in the back_populates, the fields didn't match. The code now:

class Estudiante(Base):
    __tablename__="alumno"   
    id=Column(Integer,Sequence('alumno_seq_id'),primary_key=True)
    cedula_identidad=Column(String)
    nombre_alumno=Column(String)
    apellido_alumno=Column(String)
    curso_idAlumno=Column(Integer,ForeignKey('curso.id'))
    
    cursos=relationship("Curso",back_populates='estudiantes')

    def __repr__(self):
        return'{}{}'.format(self.nombre_alumno, self.apellido_alumno)

class Curso(Base):
    __tablename__='curso'
    id=Column(Integer, Sequence('curso_seq_id'),primary_key=True)
    nombre_curso=Column(String)
        
    estudiantes=relationship("Estudiante",back_populates='cursos')
    hora_curso=relationship("Horarios",back_populates='curso_hora')
    def __repr__(self):
        return'{}'.format(self.nombre_curso)

class Horarios(Base):
    __tablename__='horario'
    id=Column(Integer, Sequence('horario_seq_id'),primary_key=True)
    dia=Column(String)
    hora_inicio=Column(String)
    hora_fin=Column(String)
    profesor_id=Column(Integer,ForeignKey('profesor.id'))
    curso_id=Column(Integer,ForeignKey('curso.id'))
    
    curso_hora=relationship("Curso",back_populates='hora_curso')
    curso_profe=relationship("Profesor",back_populates='profe_curso')

    def __repr__(self):
        return'{}{}{}'.format(self.dia,self.hora_inicio, self.hora_fin,\
        self.cedula_identidad)

class Profesor(Base):
    __tablename__='profesor'
    id=Column(Integer, Sequence('profesor_seq_id'),primary_key=True)
    cedula_identidad=Column(String)    
    nombre_profesor=Column(String)
    apellido_profesor=Column(String)
    
    profe_curso=relationship("Horarios",back_populates='curso_profe')
    def __repr__(self):
        return'{}{}{}'.format(self.nombre_profesor, self.apellido_profesor,
        self.cedula_identidad)

So thanks for your kindness

I'm using FastAPI and got the same issue.
If you guys using the same, maybe check what i've done to resolve this issue:
So it's because of wrong relation declaration in models.
The correct one is something like this:

class Book(Base):
    __tablename__ ="book"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)

    # relation
    bookmark = relationship("BookMark", back_populates="book")


class BookMark(Base):
    __tablename__ ="bookmark"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)
    book_id = Column(Integer, ForeignKey("book.id"), nullable=False)

    # relation
    book = relationship("Book", back_populates="bookmark")

It have to be declare relation in both table, if you missing one, then issue will appear.
Back there, i was missing the relation in Book table, so it causing the issue.
Hope this help.

Related