이 가이드에 따라 SQLAlchemy 관계 예제를 시도 할 때 : 기본 관계 패턴
이 코드가 있습니다
#!/usr/bin/env python
# encoding: utf-8
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base(bind=engine)
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'))
parent = relationship("Parent")
Base.metadata.create_all()
p = Parent()
session.add(p)
session.commit()
c = Child(parent_id=p.id)
session.add(c)
session.commit()
print "children: {}".format(p.children[0].id)
print "parent: {}".format(c.parent.id)
잘 작동하지만 가이드에서는 모델이 다음과 같아야한다고 말합니다.
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
**children = relationship("Child", 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="children")**
이유는 필요하지 않습니다 back_populates또는 backref내 예? 둘 중 하나를 언제 사용해야합니까?
back_populatesvsbackref: 에 대한 메모는backref두 클래스 모두에서 관계를 선언 할 필요가 없기 때문에 더 간결하지만 실제로는 이것을 온라인에 저장할 가치가 없습니다.back_populates파이썬 문화에서 "명시적인 것이 암시적인 것보다 낫다" (Zen of Python)뿐만 아니라 많은 모델이있을 때 그 선언을 한 눈에 볼 수 있기 때문에 더 낫다고 생각 합니다. 모든 관련 모델. 또한,의 좋은 측면 혜택은back_populates대부분의 IDE =)에 자동 완성 양쪽 방향에서 얻을 수 있다는 것입니다