15

我在将表与不同文件中的关系分开时遇到问题。我希望下面的表格位于三个单独的文件中并在第三方页面中导入TableA ,但我无法管理加载顺序。

在大多数情况下,我都会收到以下错误。

sqlalchemy.exc。 InvalidRequestError:初始化映射器 Mapper|TableA|tablea 时,表达式 'TableB' 未能找到名称(“名称 'TableB' 未定义”)。如果这是一个类名,请考虑在定义了两个依赖类之后将此 relationship() 添加到该类中。

class TableA(Base):
    __tablename__ = "tablea"
   id = Column(Integer, primary_key=True)
   name = Column(String)

   tableB = relationship("TableB", secondary = TableC.__table__)

class TableB(Base):
   __tablename__ = "tableb"
   id = Column(Integer, primary_key=True)
  name = Column(String)

class TableC(Base):
   __tablename__ = "tableab"
   tableAId = Column("table_a_id", Integer, ForeignKey("TableA.id"), primary_key=True)
   tableBId = Column("table_b_id", Integer, ForeignKey("TableB.id"), primary_key=True)
4

2 回答 2

12

这应该可以工作(注意 TableC.被替换为表名以避免循环模块加载):

### base.py
engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)
Base = declarative_base(bind=engine)

### classA.py
from base import Base
from classB import TableB

class TableA(Base):
    __tablename__ = 'tablea'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    tableBs = relationship("TableB", secondary="tableab")
    #tableBs = relationship("TableB", secondary=TableC.__table__)

### classB.py
from base import Base

class TableB(Base):
    __tablename__ = 'tableb'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))

### classC.py
from base import Base
from classA import TableA
from classB import TableB

class TableC(Base):
    __tablename__ = 'tableac'
    tableAId = Column(Integer, ForeignKey("tablea.id"), primary_key=True, )
    tableBId = Column(Integer, ForeignKey("tableb.id"), primary_key=True, )

### main.py
from base import Base, Session, engine
from classA import TableA
from classB import TableB
from classC import TableC
Base.metadata.create_all(engine)

此外,我相信 ForeignKey 参数区分大小写,因此您的代码可能无法正常工作,因为“TableA.id”在区分大小写时与“tablea”名称不匹配。

于 2012-06-15T14:18:46.797 回答
1
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()


class Parent(Base):
    __tablename__ = 'Parent'
    ParentID = Column(Integer, primary_key=True)
    Description = Column(String)

    def __init__(self, ParentID, Description):
        self.ParentID = ParentID
        self.Description = Description
----------------------------------------------------------------------

from sqlalchemy import Column, String, Integer, ForeignKey
import Parent
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()


class Child(Base):
    __tablename__ = "Child"
    ChildID = Column(Integer, primary_key=True)
    Description = Column(String)
    ParentID = Column('CompanyID', Integer, ForeignKey(Parent.ParentID))

    def __init__(self, ChildID, Description,ParentID):
        self.ChildID = ChildID
        self.Description = Description
        self.ParentID=ParentID
于 2019-01-01T10:19:53.307 回答