在SQLAlchemy中,如何在2个不同的.py文件中创建ForeignKey关系?

时间:2011-11-24 20:06:11

标签: mysql database orm sqlalchemy

user_models.py中,我有这个:

class Users(Base):
    __tablename__ = 'account_users'
    id = Column(Integer, primary_key = True)
    username = Column(String(255), nullable=False)    
Base.metadata.create_all(engine)

当我运行它时,我创建了一个用户表。

在我的另一个档案groups_models.py上,我有这个:

class Groups(Base):
    __tablename__ = 'personas_groups'
    id = Column(Integer, primary_key = True)
    user_id = Column(Integer, ForeignKey('account_users.id')) #This creates an error!!!
    user = relationship('Users') #this probably won't work. But haven't hit this line yet.

Base.metadata.create_all(engine)

所以,正如你所看到的,我想从群组中建立多对一的关系 - >用户。

但是当我运行groups_models.py时...我收到此错误:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'personas_groups.user_id' could not find table 'account_users' with which to generate a foreign key to target column 'id'

如果我把两张桌子放在一个文件中,我相信它可以工作......但因为我将它分成2个文件(我绝对必须这样做)...我不知道怎么做ForeignKey关系再工作了吗?

1 个答案:

答案 0 :(得分:20)

关键是对两个外键使用相同的Base,而不是为每个表创建一个新的。

basetest.py

from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Column, Integer, String
from sqlalchemy import Table, Text

engine = create_engine('mysql://test:test@localhost/test1',
                    echo=False)

Base = declarative_base()

user_models.py

from sqlalchemy import Column, Integer, String
from sqlalchemy import Table, Text


#Base = declarative_base()
from basetest import Base

class Users(Base):
    __tablename__ = 'account_users'
    __table_args__ = {'extend_existing':True}
    id = Column(Integer, primary_key = True)
    username = Column(String(255), nullable=False)    

Base.metadata.create_all(engine)

groups_models.py

from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Column, Integer, String
from sqlalchemy import Table, Text

from basetest import Base
#Base = declarative_base()
from test1 import Users

class Groups(Base):
    __tablename__ = 'personas_groups'
    __table_args__ = {'extend_existing':True}
    id = Column(Integer, primary_key = True )
    user_id = Column(Integer, ForeignKey('account_users2.id')) #This creates an error!!!
    user = relationship(Users) #this probably won't work. But haven't hit this line yet.

Base.metadata.create_all(engine)

确保您拥有相同的Base来创建所有相关的表格。