ABOUT ME

-

  • [sqlalchemy] 테이블간 relationship 설정
    SQL 2021. 7. 26. 14:58

     

    테이블간 one to many등과 같은 관계가 있을때,

    sqlslachemy의 relationship을 통해서 해당 관계를 지정할 수 있다. 

    테이블을 생성할 때 추가해주면 된다. 

     

    공식문서:

    https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html

     

    Relationship 설정 1 - #backref 사용하기

    relationship('Class명', backref ='해당테이블 명')

    class User(Base):
    
        __tablename__ = 'user'
    
        id = Column(Integer, primary_key=True)
        screen_name = Column(String)
        tweets = relationship('Tweet', backref='user')
    
        def __repr__(self):
            return f"User({self.id})"
    
    
    class Tweet(Base):
    
    
        __tablename__ = 'tweet'
    
        id = Column(Integer, primary_key=True)
        full_text = Column(String)
        user_id = Column(Integer, ForeignKey('user.id'))
    
        def __repr__(self):
            return f"Tweet({self.id})"

     

     

     

    Relationship 설정 1 - #back_populates사용하기 

    pair 짝이 맞아야하고, back_populates에 적은 name명이 같아야 한다. 

     

     

    tweet_ = db.relationship('Tweet', back_populates = 'user_', cascade='all, delete')

    user_ = db.relationship('User', back_populates = 'tweet_')

     

     

    class Address(Base):
        __tablename__ = "Address"
    
        address_id = Column(Integer, primary_key=True, nullable=False)
        city = Column(String(48))
        street = Column(String(128))
        customer_id = Column(Integer, ForeignKey('Customer.customer_id'))
    
        invoice_Item = relationship('Invoice_Item', back_populates='address', cascade='all, delete') #primary - 0ne:Many 에서 one쪽
    
    
    class Invoice_Item(Base):
        __tablename__ = 'Invoice_Item'
        ii_id = Column(Integer, primary_key=True, nullable=False)
        invoice_date = Column(DateTime, nullable=False)
        address_id = Column(Integer, ForeignKey('Address.address_id'))
        item_id = Column(Integer, ForeignKey('Item.item_id'))
    
        address = relationship('Address', back_populates='invoice_Item')

     

    foreign Key에서는 Table명,

    relationship에서는 Class명으로 설정한다 

    'SQL' 카테고리의 다른 글

    [HackerRank] Top Competitors  (0) 2021.09.28
    [HackerRank] Binary Tree Nodes  (0) 2021.09.23
    [HackerRank] Weather Observation Station 5  (0) 2021.09.23
    [필기] DB - SQL쿼리 - ORM  (0) 2021.07.29
    [MySQL-일기장] COUNT(*) 는 NULL을 포함한다  (0) 2021.07.22

    댓글