sqlalchemy经典映射关系问题

时间:2016-12-28 15:22:26

标签: python sqlalchemy

我的使命是终于学习sqlAlchemy,这样我才能在未来几年中获益。

我对sqlalchemy文件深有感触,并且已经过去两天了。我很想学习经典的映射方式,而不是声明性的,bc我想要连接的db存在,并且在它的所有表中都没有唯一的id列。 According to this article classical mapping is the way to go under such circumstances

我一直在关注sqlalchemy网站上的经典示例,但我似乎无法找到正确的关系配置来实现这一点。

这是我的所有代码:

engine = create_engine(
    "mssql+pyodbc://someaddress/test?driver=FreeTDS?TDS_version=8.0", echo=True)

metadata = MetaData(engine)

class User(object):

    def __repr__(self):
        return "<User(User_id='%s', name='%s', age='%s')>" % (
                            self.user_id, self.name, self.age)
class Email(object):

    def __repr__(self):
        return "<User(email_id='%s', address='%s', user_id='%s')>" % (
                            self.email_id, self.address, self.user_id)

users = Table('users', metadata,
    Column('user_id', Integer, primary_key=True),
    Column('name', String(40)),
    Column('age', Integer),
    schema='test.dbo.users')

mapper(User, users, properties={'Email': relationship(Email, primaryjoin=users.c.user_id==emails.c.user_id)})

emails = Table('emails', metadata,
    Column('email_id', Integer, primary_key=True),
    Column('address', String),
    Column('user_id', Integer, ForeignKey('test.dbo.users.user_id')),
    schema='test.dbo.emails')

mapper(Email, emails)

Session = sessionmaker(bind=engine)
session = Session()

mary = session.query(User, Email).filter(User.user_id == Email.user_id)

追踪错误消息表明,映射器/关系就是问题所在。

InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers.  Original exception was: Could not determine join condition between parent/child tables on relationship User.Email - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

我尝试了很多不同的东西来尝试补救,但我无法深究它。

非常感谢任何正确方向的指针!

我所使用的sqlalchemy版本是;

'1.0.12'

1 个答案:

答案 0 :(得分:2)

我好运:

Column('user_id', Integer, ForeignKey('users.user_id')),

我还重新排序了表格和映射代码:

users = Table('users', metadata,
    Column('user_id', Integer, primary_key=True),
    Column('name', String(40)),
    Column('age', Integer))

emails = Table('emails', metadata,
    Column('email_id', Integer, primary_key=True),
    Column('address', String),
    # foreign key to table users
    Column('user_id', Integer, ForeignKey('users.user_id')))

mapper(Email, emails)

mapper(User, users, properties={
    'Email': relationship(
        Email, primaryjoin=users.c.user_id==emails.c.user_id)})