SQLAlchemy错误查询跨数据库连接

时间:2014-05-20 00:24:25

标签: python database join sqlalchemy

我有多个sqlite数据库。

我在下面的代码中尝试从'Owner1'获取构造数据:

sess.query(Construction).select_from(join_(Owner)).filter(Owner.name == 'Owner 1').all()

sess.query(Construction).select_from(join_(Owner, Construction)).filter(Owner.name == 'Owner 1').all()

但是这给了我以下错误:

sqlalchemy.exc.OperationalError: (OperationalError) no such table: owner

任何人都可以帮我解决这个问题。提前致谢 我正在使用Python 3.4和sqlalchemy 0.9.4

这里是来源:

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from datetime import date

engines = {'o': create_engine('sqlite:///master.db', echo=True),
    'c': create_engine('sqlite:///struct.db', echo=True),
    't': create_engine('sqlite:///trade.db', echo=True)}

class Base(object):

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    id = Column(Integer, primary_key=True)

Base = declarative_base(cls=Base)

class OBase(Base):
    __abstract__ = True

    metadata = MetaData(bind=engines.get('o'))

class CBase(Base):
    __abstract__ = True

    metadata = MetaData(bind=engines.get('c'))

class TBase(Base):
    __abstract__ = True

    metadata = MetaData(bind=engines.get('t'))

class Owner(OBase):

    name = Column(String)
    address = Column(String)

class Construction(CBase):

    description = Column(String)
    value = Column(Integer)

    owner_id = Column(Integer, ForeignKey(Owner.id))
    owner = relationship(Owner)

class Trading(TBase):

    number = Column(String)
    date = Column(Date)
    value = Column(Integer)

    owner_id = Column(Integer, ForeignKey(Owner.id))
    owner = relationship(Owner)

OBase.metadata.create_all()
CBase.metadata.create_all()
TBase.metadata.create_all()

Session = scoped_session(sessionmaker())

sess = Session()

o1 = Owner(name='Owner 1', address='123 anywhere street')
o2 = Owner(name='Owner 2', address='40 main street')

sess.add_all([Construction(description='Flooring', value=1000, owner=o1),
    Construction(description='Flooring', value=1500, owner=o2),
    Construction(description='Roof', value=900, owner=o1)])
sess.commit()

1 个答案:

答案 0 :(得分:1)

问题是生成的查询不是"跨数据库",它使用Construction的引擎执行,并且其数据库确实没有Owner的表。

您可以分两步完成:获取所有者的id,然后搜索Construction

如果只有一位老板:

owner = sess.query(Owner).filter(Owner.name = 'Owner 1').one()
q = sess.query(Construction).filter(Construction.owner_id == owner.id)

如果是多个所有者:

owners = sess.query(Owner).filter(Owner.name.like('Owner 1%')).all()
ids = (_.id for _ in owners)
q = sess.query(Construction).filter(Construction.owner_id.in_(ids))