使用SQLAlchemy检索多对多关系属性

时间:2010-02-07 17:03:15

标签: python sql sqlalchemy declarative turbogears

我有一对多关系,其中关系表包含的列数多于主键。例如,考虑一个幻灯片放映系统,其中每个图像可以拥有自己的超时,并根据幻灯片显示不同的超时。一个愚蠢的例子,但它必须为了说明而做;)

所以我想我会做类似以下的事情(使用Declarative):

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

1 个答案:

答案 0 :(得分:1)

您可以基于show_has_image表定义中间模型(使用复合主键)并定义与之的关系。然后使用association_proxy定义Show.images属性。

相关问题