【发布时间】:2012-05-28 20:29:54
【问题描述】:
我尝试使用sqlaclhemy连接表继承,出现了奇怪的情况。
class CommonObject(Base):
__tablename__ = "objects"
id = Column("objid", Integer, primary_key=True)
objname = Column(String(32))
...
class GoodsPlacement(Container, Loadable, Dumpable):
__tablename__ = "goods_placements"
id = Column("objid", Integer, ForeignKey("containers.objid"), primary_key=True)
...
class Departure(CommonObject):
__tablename__ = "departures"
id = Column(Integer, ForeignKey("objects.objid"), primary_key=True)
content_id = Column(Integer, ForeignKey("goods_placements.objid"))
content = relationship("GoodsPlacement",
primaryjoin="Departure.content_id==GoodsPlacement.id",
foreign_keys=[content_id],
lazy='joined',
backref="departures")
...
当我写查询时:
session.query(GoodsPlacement).filter(~GoodsPlacement.departures.any(Departure.status_id < 2))
它给我带来了这样的东西:
SELECT
objects.objid AS objects_objid,
goods_placements.objid AS goods_placements_objid,
objects.objname AS objects_objname
FROM objects
JOIN goods_placements ON objects.objid = goods_placements.objid
WHERE NOT (EXISTS (
SELECT 1
FROM (
SELECT
objects.objid AS objects_objid,
objects.objname AS objects_objname,
departures.id AS departures_id,
departures.content_id AS departures_content_id,
departures.status_id AS departures_status_id
FROM objects
JOIN departures ON objects.objid = departures.id)
AS anon_1, objects
WHERE anon_1.departures_content_id = objects.objid
AND anon_1.departures_status_id < :status_id_1)
)
这不起作用,因为存在子句中的对象覆盖了外部对象。 由于我使用的解决方法直接来自 sqlexpression,
session.query(GoodsPlacement).filter(~exists([1],
and_("departures.status_id<2",
"departures.content_id=goods_placements.objid"),
from_obj="departures"))
但它很大程度上取决于列名和表名。
如何在exists语句中为对象表指定别名?
Debian wheezy,python-2.7.3rc2,sqlaclhemy 0.7.7-1
【问题讨论】:
-
能否请您添加
query定义的其余部分,而不仅仅是filter部分。 -
session.query(GoodsPlacement).filter(...).all()
-
这些映射不完整。 GoodsPlacement 是 CommonObject 的子类吗?您能否制定一个完整的复制示例(不包括与错误生成的查询无关的内容)并通过电子邮件发送 SQLAlchemy 列表。连接表继承映射器之间的通用关系非常复杂。
-
门票已添加sqlalchemy.org/trac/ticket/2491 和sqlalchemy.org/trac/ticket/2492。直到 0.8 版本改进了 any() 的机制后,该错误才可能得到修复。
标签: python sqlalchemy exists declarative class-table-inheritance