SQLAlchemy: Getting a single object from joining multiple tables

前端 未结 3 582
说谎
说谎 2021-01-01 01:32

DB - SQLAlchemy setting

Consider a classic setting of two tables - user and api_key, represented by SQLAlchemy objects as:



        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 02:19

    I would add an api_key relationship on User:

    class User(Base):
        __tablename__ = 'user'
        user_id = Column(String)
        user_name = Column(String)
        vioozer_api_key = Column(String, ForeignKey("api_key.api_key"))
        api_key = Relationship('ApiKey', uselist=False)
    

    Then you can do a query like this:

    >>> user = database.db_session.query(User)\
          .filter(User.user_id=='user_00000000000000000000000000000000').first()
    >>> user.api_key
    
    

提交回复
热议问题