开发者

How to create relationships from existing relationships in SQLAlchemy?

I'm getting a bit stuck with relationships within relationships in sqlalchemy. I have a model like this:

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):
    __t开发者_C百科ablename__ = '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)

So there is one-to-many between shows and episodes, and many-to-many between episodes and writers, but I now want to create a many-to-many relationship between shows and writers, based on the fact that a writer is associated with an episode of a show. I tried to add another column to the assoc table but that results in the following exception:

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.

So I'm obviously doing something wrong with my relationship declarations. How do I create the right primaryjoins to achieve what I'm trying to do here?


The fix is suggested right in the error message. Anyway, you have no need for a column that denormalises your schema; writer.shows can be an associationproxy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜