我有一个多对多关系,其中关系表包含的列多于主键。例如,考虑一个幻灯片放映系统,其中每个图像都可以有自己的超时时间,并且根据幻灯片放映不同的超时时间。一个愚蠢的例子,但为了说明,它必须这样做;)
所以我想我会做以下事情(使用声明式):
show_has_image = Table( 'show_has_image',
DeclarativeBase.metadata,
Column( 'show_id', Integer, ForeignKey( 'show.id' ) ),
Column( 'image_id', Integer, ForeignKey( 'image.id' ) ),
Column( 'timeout', Integer, default=5 ),
PrimaryKeyConstraint( 'show_id', 'image_id' )
)
class Show(DeclarativeBase):
__tablename__ = "show"
id = Column( Integer, primary_key = True )
name = Column( Unicode(64), nullable = False)
class Image(DeclarativeBase):
__tablename__ = "image"
id = Column( Integer, primary_key = True )
name = Column( Unicode(64), nullable = False)
data = Column(Binary, nullable = True)
show = relation( "Show",
secondary=show_has_image,
backref="images" )
我将如何访问“超时”值?我在文档中找不到任何关于此的内容。到目前为止,检索图像很简单:
show = DBSession.query(Show).filter_by(id=show_id).one()
for image in show.images:
print image.name
# print image.timeout <--- Obviously this cannot work, as SA has no idea
# how to map this field.
我很乐意让它按照我在前面的代码中概述的方式工作。当然,我可以timeout
在类中添加一个属性来Image
动态获取值。但这会导致不必要的 SQL 查询。
我宁愿在一个查询中全部返回。在 SQL 中很容易:
SELECT i.name, si.timeout
FROM show s
INNER JOIN show_has_image si ON (si.show_id = s.id)
INNER JOIN image i ON (si.image_id = i.id)
WHERE s.id = :show_id