2017-03-30 5 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 

任意のアイデアが間違って何ですか?あなたがエラーを取得なぜあなたはPythonでclass constructionにご理解をリフレッシュする必要があります理解する

答えて

0

:あなたの例では

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オブジェクトを介して列にアクセス

関連する問題