I'm trying to build a many to many relationship with sqlalchemy with pyodbc and SQL Server , and here is my code:
from sqlalchemy import Table, Text
from sqlalchemy import ForeignKey
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
courses_students = Table('courses_students',Base.metadata,
Column('stu_id',ForeignKey('student.id'),primary_key=True),
Column('cour_id',ForeignKey('course.id'),primary_key=True),
Column('grade',Integer())
)
# from sqlalchemy.ext.declarative import declarative_base
# Base = declarative_base()
class Student(Base):
__tablename__ = 'student'
stu_id = Column('id',Integer,primary_key=True)
name = Column('name',String(10))
stu_class = Column('class',String(10))
#courses = relationship('Course',secondary=courses_students,back_populates='students')
def __init__(self,stu_id,name,stu_class):
self.stu_id = stu_id
self.name = name
self.stu_class = stu_class
def __repr__(self):
_str = "Student({_id},{_name},{_class})".format(_id=self.stu_id,_name=self.name,
_class=self.stu_class)
return _str
# from sqlalchemy.ext.declarative import declarative_base
# Base = declarative_base()
class Course(Base):
__tablename__ = 'course'
cour_id = Column('id',Integer,primary_key=True)
name = Column('name',String(20))
teacher_name = Column('teacher_name',String(10))
credit = Column('credit',Integer())
students = relationship('Student',secondary=courses_students,backref='courses')
def __init__(self,c_id,name,t_name,credit):
self.cour_id = c_id
self.name = name
self.teacher_name = t_name
self.credit = credit
def __repr__(self):
_str = "Course({_id},{_na},{_t_na},{_cre})".format(_id=self.cour_id,_na=self.name,
_t_na=self.teacher_name,
_cre=self.credit)
return _str
However, when I tried to add data with session.add(), I met the following errors:
InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|Student|student'. Original exception was: When initializing mapper Mapper|Student|student, expression 'course' failed to locate a name ("name 'course' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.