I'm trying to figure out how to distribute SQLAlchemy classes across multiple files, and in my life I may not understand how to do this. I'm new to SQLAlchemy, so forgive me if this question is trivial.
Consider these 3 classes in each of our files:
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"))
And then let's say that we have main.py something like this:
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 = AA() b1 = BB() b2 = BB() c1 = CC() c2 = CC() a.Bs.append(b1) a.Bs.append(b2) a.Cs.append(c1) a.Cs.append(c2) session.add(a) session.commit()
The above error:
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'
How can I provide a declarative base in these files?
What is the “right” way to do this, given that I could add something like Pylons or Turbogears on top of this?
change 10-03-2011
I found this description from the Pyramids framework, which describes the problem and, more importantly, checks that this is an actual problem, and not (only) just my confused self that the problem is. I hope this helps others who dare to take this dangerous road :)