0
我有一個多對多的關係,其中關係表包含的列數多於只有主鍵。作爲一個例子,考慮一個幻燈片放映系統,其中每個圖像可能有自己的超時時間,並根據幻燈片顯示不同的超時時間。一個愚蠢的例子,但它會爲說明起見做;)使用SQLAlchemy檢索多對多關係屬性
所以我想我會做類似如下(使用聲明):
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
這似乎是沿着我所尋找的線。不幸的是,它在Turbogears中打破了「貓步」。因爲 - 在目前的應用程序狀態 - 我依靠時裝表演,我還不能使用這個。但我稍後再看看。如果應用程序超過了第一個「概念驗證」演示。 – exhuma 2010-03-22 16:37:29