Python 使用SQLAlchemy和SQL server向数据库添加数据时出现InvalidRequestError

Python 使用SQLAlchemy和SQL server向数据库添加数据时出现InvalidRequestError,python,sqlalchemy,Python,Sqlalchemy,我正在尝试使用pyodbc和SQL Server与sqlalchemy建立多对多关系,下面是我的代码: from sqlalchemy import Table, Text from sqlalchemy import ForeignKey from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() courses_students = Table('courses_students',Ba

我正在尝试使用pyodbc和SQL Server与sqlalchemy建立多对多关系,下面是我的代码:

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
但是,当我尝试使用
session.add()
添加数据时,遇到以下错误:

InvalidRequestError:一个或多个映射程序未能初始化-无法继续初始化其他映射程序。触发映射器:“映射器|学生|学生”。最初的例外情况是:初始化映射器映射器|学生|学生时,表达式“课程”未能找到名称(“名称“课程”未定义”)。如果这是类名,那么在定义了依赖类之后,考虑将此关系()添加到类。
该特定错误是由键入错误和在注释掉它们之前创建的单独的
Base
类引起的。我假设模型定义最初在单独的文件中

relationship()
需要一个映射类或一个解析为的字符串,例如第一个参数,但您传递了它
'course'
,它解析为类映射到的
表。在这里的示例中,您似乎已经更正了对
“课程”
的引用

指定传递给
relationship()
的类的字符串参数在期间通过从与
Base
关联的类注册表中查找来解析。但是在您的示例中,您已经为每个模型和关联的
表创建了单独的
基本类
,因此查找失败,因为这些类都位于单独的注册表中

首次使用
会话
时会引发错误,因为映射器是惰性配置的。另一方面,可用于显式配置任何挂起的更改

您对
课程的定义中潜伏着另一个错误
:您使用了
backref='courses'
而不是
back\u populates='courses'
,因此在配置过程中出现以下错误:

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'
回溯(最近一次呼叫最后一次):
文件“wtf.py”,第60行,在
配置映射器()
文件“~/Work/sqlalchemy/lib/sqlalchemy/orm/mapper.py”,第3029行,在configure\u mappers中
映射程序。_post_configure_properties()
文件“~/Work/sqlalchemy/lib/sqlalchemy/orm/mapper.py”,第1828行,在“post\u configure\u properties”中
prop.init()
文件“~/Work/sqlalchemy/lib/sqlalchemy/orm/interfaces.py”,第184行,在init中
self.do_init()
文件“~/Work/sqlalchemy/lib/sqlalchemy/orm/relationships.py”,第1659行,在do_init中
self.\u生成\u backref()
文件“~/Work/sqlalchemy/lib/sqlalchemy/orm/relationships.py”,第1849行,在_generate\u backref中
(背向参考键,self,m))
sqlalchemy.exc.ArgumentError:在关系“Course.students”上创建backref“courses”时出错:映射器“mapper | Student | Student”上存在该名称的属性