SQLAlchemy Join #2 Many To One
Many To One
λ€λμΌ κ΄κ³μμ child λ₯Ό μ°Έμ‘°νλ μΈλν€λ parent ν΄λμ€μ μμΉν΄μλ€. relationship()
ν¨μ
λ parent ν΄λμ€μ μμΉν΄μμΌλ©°, scalar-holding μμ±μ΄ μμ±λ κ²μ΄λ€.
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)
μλ°©ν₯ μ°κ²°μ λλ²μ§Έ relationship()
λ₯Ό μΆκ°νκ³ μμͺ½μrelationship.back_populates
νλΌλ―Έν°λ₯Ό μμͺ½μ μ μ©νλ©΄ λλ€.
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'))
child = relationship("Child", back_populates="parents")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parents = relationship("Parent", back_populates="child")
λμμΌλ‘λ backref
νλΌλ―Έν°λ₯Ό νμͺ½μ relationship()
μ μ μ©νλ©΄ λλ€.
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'))
child = relationship("Child", backref="parents")
νμ ν μ€νΈ
μλμ κ°μ΄ μμ λͺ¨λΈ ν΄λμ€λ€μ νΈμΆνλ μ½λλ₯Ό μ§λ΄€λ€. μ νΈμΆμ΄ λλ€. back_populates
λ₯Ό μ΄μ©ν΄μλ parents κ° Child ν΄λμ€μ μ μκ° λμ΄ μμΌλ μ€νλλκ² λ§λλ°, backref
μ κ²½μ° Parent ν΄λμ€μ μ μκ° λμ΄ μλλ° c.parents λ p.child.parents λΆλΆμ΄ μ μλ¬κ° μλ κΉ?
from model import session
from model import Child
from model import Parent
p = session.query(Parent).filter(Parent.id == 1).scalar()
print(p.id)
print(p.child)
print(p.child.id)
print(p.child.parents)
c = session.query(Child).filter(Child.id == 12).scalar()
print(c)
print(c.id)
print(c.parents)
session.close()
backref μ back_populates μ μ°¨μ΄λ λκΉ?
backref: κ΄κ³λ λ§€νΌ ν΄λμ€μ μμ±μ λ¬Έμμ΄ μ΄λ¦μ κ°λ¦¬ν¨λ€. μ΄ μμ±μ λ§€νΌ ν΄λμ€κ° ꡬμ±λ λ μλμ μΌλ‘ μμ±λλ€.
back_popuplates: backref μ λμΌν μλ―Έμ΄κ³ , μλμ μΌλ‘ μμ±ν΄μ£Όμ§ μλκ²μ΄ μ°¨μ΄. λ§€νΌ ν΄λμ€μ λͺ μμ μΌλ‘ ꡬμ±ν΄μ€μΌ νλ€.
Parent λ§€νΌ ν΄λμ€μμ back_populates
λ‘ μ§μ ν parents κ° λ§μ½ Child λ§€νΌ ν΄λμ€μμ μ μΈνμ§ μμλ€λ©΄ μλμ κ°μ μλ¬κ° λ°μνλ€.
sqlalchemy.exc.InvalidRequestError: Mapper 'Mapper|Child|child' has no property 'parents'