【问题标题】:Retrieving many-to-many relation properties using SQLAlchemy使用 SQLAlchemy 检索多对多关系属性
【发布时间】:2010-02-07 17:03:14
【问题描述】:

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

所以我想我会做以下事情(使用声明式):

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

【问题讨论】:

    标签: python sql sqlalchemy declarative turbogears


    【解决方案1】:

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

    【讨论】:

    • 这似乎符合我正在寻找的内容。不幸的是,它打破了 Turbogears 中的“走秀”。因为 - 在应用程序的当前状态下 - 我依赖猫步,我还不能使用它。但我稍后再看看。如果应用通过了第一个“概念验证”演示。
    猜你喜欢
    • 2016-12-03
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多