How do I join three tables with SQLalchemy and keeping all of the columns in one of the tables?

后端 未结 3 1370
情话喂你
情话喂你 2021-02-02 03:01

So, I have three tables:

The class defenitions:

engine = create_engine(\'sqlite://test.db\', echo=False)
SQLSession = sessionmaker(bind=engine)
Base = de         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 04:02

    To make this a little easyer I've added relationships to your model, that way you can just do user.subscriptions to get all the subscriptions.

    engine = create_engine('sqlite://test.db', echo=False)
    SQLSession = sessionmaker(bind=engine)
    Base = declarative_base()
    
    class Channel(Base):
        __tablename__ = 'channel'
    
        id = Column(Integer, primary_key = True)
        title = Column(String)
        description = Column(String)
        link = Column(String)
        pubDate = Column(DateTime)
    
    class User(Base):
        __tablename__ = 'user'
    
        id = Column(Integer, primary_key = True)
        username = Column(String)
        password = Column(String)
        sessionId = Column(String)
    
    class Subscription(Base):
        __tablename__ = 'subscription'
    
        userId = Column(Integer, ForeignKey('user.id'), primary_key=True)
        user = relationship(User, primaryjoin=userId == User.id, backref='subscriptions')
        channelId = Column(Integer, ForeignKey('channel.id'), primary_key=True)
        channel = relationship(channel, primaryjoin=channelId == channel.id, backref='subscriptions')
    
    results = session.query(
        Channel.id,
        Channel.title,
        Channel.subscriptions.any().label('subscribed'),
    )
    
    for channel in results:
        print channel.id, channel.title, channel.subscribed
    

提交回复
热议问题