Simplified, I have the following class structure (in a single file):
Base = declarative_base() class Item(Base): __tablename__ = 'item' id = Column(BigInteger, primary_key=True) # ... skip other attrs ... class Auction(Base): __tablename__ = 'auction' id = Column(BigInteger, primary_key=True) # ... skipped ... item_id = Column('item', BigInteger, ForeignKey('item.id')) item = relationship('Item', backref='auctions')
I get the following error from this:
sqlalchemy.exc.InvalidRequestError InvalidRequestError: When initializing mapper Mapper|Auction|auction, expression 'Item' failed to locate a name ("name 'Item' is not defined"). If this is a class name, consider adding this relationship() to the Auction class after both dependent classes have been defined.
I'm not sure how Python cannot find the Item class, as even when passing the class, rather than the name as a string, I get the same error. I've been struggling to find examples of how to do simple relationships with SQLAlchemy so if there's something fairly obvious wrong here I apologise.
This all turned out to be because of the way I've set SQLAlchemy up in Pyramid. Essentially you need to follow this section to the letter and make sure you use the same declarative_base
instance as the base class for each model.
I was also not binding a database engine to my DBSession
which doesn't bother you until you try to access table metadata, which happens when you use relationships.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With