过滤父母与sqlalchemy的多对多关系

时间:2017-01-12 17:24:43

标签: python join sqlalchemy

假设我有以下三个描述音乐集的类:

from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint
from sqlalchemy import Table
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base


TRACK_NAME_LEN = 64
ALBUM_NAME_LEN = 64
TAG_NAME_LEN = 64
URL_LEN = 255


Base = declarative_base()


class Track(Base):

    __tablename__ = 'tracks'

    id = Column(Integer, primary_key=True)
    name = Column(String(TRACK_NAME_LEN), nullable=False)

    # many -> one
    album_id = Column(Integer, ForeignKey('albums.id'), nullable=True)
    album = relationship('Album', back_populates='tracks')


# Auxiliary table for many <--> many relationship    
album_tag = Table('album_tag', Base.metadata,
        Column('album_id', Integer, ForeignKey('albums.id')),
        Column('tag_id', Integer, ForeignKey('tags.id')))


class Album(Base):

    __tablename__ = 'albums'

    id = Column(Integer, primary_key=True)
    name = Column(String(ALBUM_NAME_LEN), nullable=False)

    # one -> many
    tracks = relationship('Track', back_populates='album')

    # many -> many
    tags = relationship(
            'Tag',
            secondary=album_tag,
            back_populates='albums')


class Tag(Base):

    __tablename__ = 'tags'

    id = Column(Integer, primary_key=True)
    name = Column(String(TAG_NAME_LEN), nullable=False, unique=True)

    # many -> many
    albums = relationship(
            'Album',
            secondary=album_tag,
            back_populates='tags')

相册可能有许多不同的标签。 我希望查询返回其相册具有给定标记的所有曲目。 这是一些不起作用的东西:

rock = session.query(Tag).filter(name='rock').one()
session.query(Track).join(Album).filter(Album.tags.any(rock))

还有其他一些失败的尝试。 我们如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

这有效:

session.query(Track).filter(Track.album.has(Album.tags.any(name='tango'))).all()