• sqlalchemy relationship

    2017. 8. 29. 15:03

    by. 위지원

    http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html


    관계에대한 이해도가 부족한것같아 공식문서를 다시읽어보았다.


    1. 1:N 관계

    class Parent(Base):
        __tablename__ = 'parent'
        id = Column(Integer, primary_key=True)
        children = relationship("Child")
    
    class Child(Base):
        __tablename__ = 'child'
        id = Column(Integer, primary_key=True)
        parent_id = Column(Integer, ForeignKey('parent.id'))



    2.N:1 관계


    class Parent(Base):
        __tablename__ = 'parent'
        id = Column(Integer, primary_key=True)
        child_id = Column(Integer, ForeignKey('child.id'))
        child = relationship("Child")
    
    class Child(Base):
        __tablename__ = 'child'
        id = Column(Integer, primary_key=True)


    3.1:1 관계


    class Parent(Base):
        __tablename__ = 'parent'
        id = Column(Integer, primary_key=True)
        child_id = Column(Integer, ForeignKey('child.id'))
        child = relationship("Child", back_populates="parent")
    
    class Child(Base):
        __tablename__ = 'child'
        id = Column(Integer, primary_key=True)
        parent = relationship("Parent", back_populates="child", uselist=False)


    4.N:M 관계

    association_table을 추가하여 두 테이블을 연결시켜준다.


    association_table = Table('association', Base.metadata, Column('left_id', Integer, ForeignKey('left.id')), Column('right_id', Integer, ForeignKey('right.id')) ) class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Child",secondary=association_table) class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True)



    정리하자면..


        child_id = Column(Integer, ForeignKey('child.id'))
    

    column에 직접넣은 지시작는 대상의 컬럼을 따르도록 하고.. ( parent가 child테이블의 id를 따르게한다) 이렇게해서 둘을 붙여주는것!


    child = relationship("Child", back_populates="parent")


    relationshion 지시자는 여기서는 parent 클래스자체가 child 클래스에 연결되어있다는 사실을 parent.chlid 속성을 통해 알 수 있게한다.

    back_populates또 역으로 클래스를 이용할수 있게 하는것이다. 


    그러니까 즉 parent를 하나 만들면 비어있는 child가 하나 생기는것이라는것 !!그래서 클래스명.클래스명 이런식으로 접근할 수 있다.


    대화의 장 💬