0
votes

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.

1

1 Answers

0
votes

That particular error was caused by a typing error and the separate Base classes you were creating before you commented them out. I assume that the model definitions were originally in separate files.

relationship() expects a mapped class or a string that resolves to such as the first argument, but you passed it 'course', which resolves to the Table the class is mapped to. It seems that in your example here you have corrected the reference to 'Course'.

A string argument naming a class passed to relationship() is resolved during mapper compilation time by looking it up from the class registry associated with Base. But in your example you have created separate Base classes for each of your models and the associative Table, so the lookup fails because the classes all reside in separate registries.

The error is raised when using the Session for the first time because mappers are configured lazily. As an aside, configure_mappers() can be used to configure any pending changes explicitly.

There's another error lurking in your definition of Course: instead of back_populates='courses' you've used backref='courses' and so during configuration the following error is raised:

Traceback (most recent call last):
  File "wtf.py", line 60, in <module>
    configure_mappers()
  File "~/Work/sqlalchemy/lib/sqlalchemy/orm/mapper.py", line 3029, in configure_mappers
    mapper._post_configure_properties()
  File "~/Work/sqlalchemy/lib/sqlalchemy/orm/mapper.py", line 1828, in _post_configure_properties
    prop.init()
  File "~/Work/sqlalchemy/lib/sqlalchemy/orm/interfaces.py", line 184, in init
    self.do_init()
  File "~/Work/sqlalchemy/lib/sqlalchemy/orm/relationships.py", line 1659, in do_init
    self._generate_backref()
  File "~/Work/sqlalchemy/lib/sqlalchemy/orm/relationships.py", line 1849, in _generate_backref
    (backref_key, self, m))
sqlalchemy.exc.ArgumentError: Error creating backref 'courses' on relationship 'Course.students': property of that name exists on mapper 'Mapper|Student|student'