SQLAlchemy Join #3 One to One
์ผ๋์ผ ๊ด๊ณ์์๋ ์์ชฝ ๋งคํผ์์ ์ค์นผ๋ผ ์์ฑ์ ํตํ ์๋ฐฉํฅ ๊ด๊ณ๊ฐ ํ์์ ์ด๋ค. ์ด๊ฒ์ ์ํด์ uselist
flag ๊ฐ ์๋๋ฐ ์ด๊ฒ์ ๋ง์์ชฝ("manyโ side of the relationship.)์ ์ปฌ๋์
๋์ ์ ์ค์นผ๋ผ ์์ฑ์ ์์น๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
์ผ๋๋ค ๋ฅผ ์ผ๋์ผ๋ก ๋ฐ๊พธ๋ฉด,
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
child = relationship("Child", uselist=False, back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship("Parent", back_populates="child")
๋ค๋์ผ์ ๊ฒฝ์ฐ,
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)
ํ์ํ ์คํธ
uselist
๋ฅผ ์ฌ์ฉํ์ง ์์ ์ํ์์ ์๋์ ์ฝ๋๋ฅผ ํตํด์ .child ์ ์ ๊ทผํ๋ฉด parent.id ==1 ์ ๋ํ ๋ฆฌ์คํธ๊ฐ ์ถ๋ ฅ ๋๋ค. ์ผ๋ฐ์ ์ธ ์ผ๋๋ค ๊ด๊ณ์์์ ์ฌ์ฉ๋ฒ์ด๋ผ๊ณ ๋ณผ ์ ์๋ค. ๋๋ฒ์งธ ๊ฒฐ๊ณผ๋ ๊ฐ์ ์ฝ๋๋ฅผ uselist=False ๋ก ์ง์ ํ๊ณ ๋์ ํธ์ถํ ์ฝ๋์ด๋ค. list ํ์์ด ์๋ Child ๊ฐ์ฒด๊ฐ ๋ณด์ฌ์ง๊ณ ์๊ณ , ์๋ ๋ฆฌ์คํธ์์ ์ฒซ๋ฒ์งธ ๊ฐ์ด ๋ณด์ฌ์ง๋ค. ์ด ๊ฒฝ์ฐ Multiple rows returned with uselist=False
๊ฒฝ๊ณ ๊ฐ ์ถ๋ ฅ๋๋ค.
p = session.query(Parent).filter(Parent.id == 1).scalar()
print(p.id)
print(p.child)
>>> [{'parent_id': 1, '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x00000000046C60F0>, 'id': 11}, {'parent_id': 1, '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x00000000046C6198>, 'id': 12}, {'parent_id': 1, '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x00000000046C6048>, 'id': 13}]
>>> {'parent_id': 1, '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x0000000003C554E0>, 'id': 11}