如何在SQLAlchemy中创建现有关系的关系?

时间:2011-06-26 14:48:54

标签: python sqlalchemy

我对sqlalchemy的关系中的关系感到有点困惑。我有这样的模型:

engine = create_engine('sqlite:///tvdb.db', echo=True)
Base = declarative_base(bind=engine)

episodes_writers = Table('episodes_writers_assoc', Base.metadata,
    Column('episode_id', Integer, ForeignKey('episodes.id')),
    Column('writer_id', Integer, ForeignKey('writers.id')),
    Column('series_id', Integer, ForeignKey('episodes.series_id'))

class Show(Base):
    __tablename__ = 'shows'

    id = Column(Integer, primary_key = True)
    episodes = relationship('Episode', backref = 'shows')

class Episode(Base):
    __tablename__ = 'episodes'

    id = Column(Integer, primary_key = True)
    series_id = Column(Integer, ForeignKey('shows.id'))
    writers = relationship('Writer', secondary = 'episodes_writers',
                           backref = 'episodes')

class Writer(Base):
    __tablename__ = 'writers'

    id = Column(Integer, primary_key = True)
    name = Column(Unicode)

所以节目和剧集之间存在一对多,剧集和作家之间存在多对多,但我现在想要在节目和作者之间建立多对多的关系,这是基于以下事实:作家与节目的剧集相关联。我尝试将另一列添加到assoc表中,但这会导致以下异常:

sqlalchemy.exc.ArgumentError: Could not determine join condition between parent/child tables on relationship Episode.writers.  Specify a 'primaryjoin' expression.  If 'secondary' is present, 'secondaryjoin' is needed as well.

所以我的关系声明显然出现了问题。如何创建正确的主连接以实现我在这里尝试做的事情?

1 个答案:

答案 0 :(得分:0)

错误消息中建议修复此问题。无论如何,您不需要一个对您的架构进行非规范化的列; writer.shows可以是一个associationproxy。