2017-03-30 52 views
0

我是SQLAlchemy的新手,嘗試爲現有數據庫設置ORM。我使用元數據設置表並自己指定外鍵。該表設置是這樣的:SQLAlchemy與多個外鍵的元數據關係

class User(Base): 
    __table__ = Table('users', metadata, 
         Column('user_id', Integer, primary_key=True), 
         autoload=True) 

class Transaction(Base): 
    __table__ = Table('transaction', metadata, 
         Column('transaction_id', Integer, primary_key=True), 
         Column('seller_id', Integer, ForeignKey('users.user_id')), 
         Column('buyer_id', Integer, ForeignKey('users.user_id')), 
         autoload=True) 
    seller = relationship('User', foreign_keys=[seller_id]) 
    buyer = relationship('User', foreign_keys=[buyer_id]) 

這不運行,出現錯誤:

NameError: name 'seller_id' is not defined 

任何想法有什麼不對?

回答

0

要理解爲什麼你的錯誤,你應該刷新您的理解上class construction在Python:

When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here.

在你的榜樣,你有沒有分配到seller_id將引入的名稱,所以使用的嘗試班級建設中的名字引發了NameError。您在課程建設期間在當前命名空間中可用的是您分配的__table__。事實上,這個確切使用情況"Using a Hybrid Approach with __table__"下記載:

class Transaction(Base): 
    __table__ = Table('transaction', metadata, 
         Column('transaction_id', Integer, primary_key=True), 
         Column('seller_id', Integer, ForeignKey('users.user_id')), 
         Column('buyer_id', Integer, ForeignKey('users.user_id')), 
         autoload=True) 
    seller = relationship('User', foreign_keys=[__table__.c.seller_id]) 
    buyer = relationship('User', foreign_keys=[__table__.c.buyer_id]) 

Note that when the __table__ approach is used, the object is immediately usable as a plain Table within the class declaration body itself, as a Python class is only another syntactical block.

換句話說,通過綁定到名稱__table__Table對象訪問列