【问题标题】:InvalidRequestError when adding data to database with SQLAlchemy and SQL server使用 SQLAlchemy 和 SQL 服务器将数据添加到数据库时出现 InvalidRequestError
【发布时间】:2018-06-05 13:27:17
【问题描述】:

我正在尝试使用 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:一个或多个映射器未能初始化 - 无法继续初始化其他映射器。触发映射器:'映射器|学生|学生'。最初的例外是:初始化映射器 Mapper|Student|student 时,表达式“课程”未能找到名称(“未定义名称“课程”)。如果这是一个类名,请考虑在定义了两个依赖类之后将此 relationship() 添加到该类中。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    该特定错误是由键入错误和您在将它们注释掉之前创建的单独的 Base 类引起的。我假设模型定义最初位于单独的文件中。

    relationship() 需要一个映射类或解析为第一个参数的字符串,但您将其传递给 'course',它解析为类映射到的 Table。在您的示例中,您似乎已更正了对'Course' 的引用。

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

    第一次使用Session 时会出现错误,因为映射器是延迟配置的。顺便说一句,configure_mappers() 可用于显式配置任何挂起的更改。

    在您对Course 的定义中潜伏着另一个错误:您使用的是back_populates='courses' 而不是backref='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'
    

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      相关资源
      最近更新 更多