我试图弄清楚如何将SQLAlchemy类分布到多个文件中,而我可以终生不搞清楚如何做到这一点。我是SQLAlchemy的新手,如果这个问题不重要,请原谅我。
在各自的文件中考虑以下三个类:
A.py:
from sqlalchemy import *
from main import Base
class A(Base):
__tablename__ = "A"
id = Column(Integer, primary_key=True)
Bs = relationship("B", backref="A.id")
Cs = relationship("C", backref="A.id")
B.py:
from sqlalchemy import *
from main import Base
class B(Base):
__tablename__ = "B"
id = Column(Integer, primary_key=True)
A_id = Column(Integer, ForeignKey("A.id"))
C.py:
from sqlalchemy import *
from main import Base
class C(Base):
__tablename__ = "C"
id = Column(Integer, primary_key=True)
A_id = Column(Integer, ForeignKey("A.id"))
然后说我们有一个main.py之类的东西:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref, sessionmaker
Base = declarative_base()
import A
import B
import C
engine = create_engine("sqlite:///test.db")
Base.metadata.create_all(engine, checkfirst=True)
Session = sessionmaker(bind=engine)
session = Session()
a = A.A()
b1 = B.B()
b2 = B.B()
c1 = C.C()
c2 = C.C()
a.Bs.append(b1)
a.Bs.append(b2)
a.Cs.append(c1)
a.Cs.append(c2)
session.add(a)
session.commit()
上面给出了错误:
sqlalchemy.exc.NoReferencedTableError: Foreign key assocated with column 'C.A_id' could not find table 'A' with which to generate a foreign key to target column 'id'
如何在这些文件之间共享声明式库?
考虑到我可能还会在上面放置诸如Pylons或Turbogears之类的东西,完成此任务的“正确”方法是什么?
编辑10-03-2011
我从Pyramids框架中找到了这个描述,该描述描述了问题,更重要的是验证了这是一个实际问题,而不仅仅是(只是)我那困惑的自我。希望它可以帮助其他敢于走这条危险道路的人:)