开发者

SQLAlchemy Self Referencing Relationship - NoReferencedTableError

I'm using SA 0.6.6, Declarative style, against Postgres 8.3, to map Python objects to a database. I have a table that is self referencing and I'm trying to make a relationship property for it's children. 开发者_StackOverflow中文版No matter what I try, I end up with a NoReferencedTableError.

My code looks exactly like the sample code from the SA website for how to do this very thing.

Here's the class.

class FilterFolder(Base):
    __tablename__ = 'FilterFolder'
    id = Column(Integer,primary_key=True)
    name = Column(String)
    isShared = Column(Boolean,default=False)
    isGlobal = Column(Boolean,default=False)
    parentFolderId = Column(Integer,ForeignKey('FilterFolder.id'))
    childFolders = relationship("FilterFolder",
                    backref=backref('parentFolder', remote_side=id)
                    )

Here's the error I get:

NoReferencedTableError: Foreign key assocated with column 'FilterFolder.parentFolderId' could not find table 'FilterFolder' with which to generate a foreign key to target column 'id'

Any ideas what I'm doing wrong here?


This was a foolish mistake on my part. I typically specify my FK's by specifying the Entity type, not the string. I am using different schemas, so when defining the FK entity as a string I also need the schema.

Broken:

parentFolderId = Column(Integer,ForeignKey('FilterFolder.id'))

Fixed:

parentFolderId = Column(Integer,ForeignKey('SchemaName.FilterFolder.id'))


I checked your code with SQLAlchemy 0.6.6 and sqlite. I was able to create the tables, add a parent and child combination, and retrieve them again using a session.query.

As far as I can tell, the exception you mentioned (NoReferencedTableError) is thrown in schema.py (in the SQLAlchemy source) exclusively, and is not database specific.

Some questions: Do you see the same bug if you use an sqlite URL instead of the Postgres one? How are you creating your schema? Mine looks something like this:

engine = create_engine(db_url)
FilterFolder.metadata.create_all(self.dbengine)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜