언제 sqlalchemy back_populates를 사용해야합니까?
이 가이드에 따라 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
내 예? 둘 중 하나를 언제 사용해야합니까?
사용 backref
하는 경우 두 번째 테이블에서 관계를 선언 할 필요가 없습니다.
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child", backref="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
를 사용 하지 않고 의를 별도로 backref
정의하는 경우을 relationship
사용하지 않으면 back_populates
sqlalchemy가 관계를 연결하는 것을 알지 못하므로 하나를 수정하면 다른 것도 수정됩니다.
So, in your example, where you've defined the relationship
's separately, but didn't provide a back_populates
argument, modifying one field wouldn't automatically update the other in your transaction.
>>> parent = Parent()
>>> child = Child()
>>> child.parent = parent
>>> print parent.children
[]
See how it didn't automatically fill out the children
field?
Now, if you supply a back_populates
argument, sqlalchemy will connect the fields.
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")
So now we get
>>> parent = Parent()
>>> child = Child()
>>> child.parent = parent
>>> print parent.children
[Child(...)]
Sqlalchemy knows these two fields are related now, and will update each as the other is updated. It's worth noting that using backref
will do this, too. Using back_populates
is nice if you want to define the relationships on every class, so it's easy to see all the fields just be glancing at the model class, instead of having to look at other classes that define fields via backref.
ReferenceURL : https://stackoverflow.com/questions/39869793/when-do-i-need-to-use-sqlalchemy-back-populates
'Development Tip' 카테고리의 다른 글
아무것도하지 않는 python pass 문에 해당하는 javascript가 있습니까? (0) | 2020.12.29 |
---|---|
오류 : EACCES 0.0.0.0:80 OSx Node.js 듣기 (0) | 2020.12.29 |
AssertionError : 뷰 함수 매핑이 기존 끝점 함수를 덮어 씁니다 : main (0) | 2020.12.28 |
오류 1148 : 사용 된 명령은이 MySQL 버전에서 허용되지 않습니다. (0) | 2020.12.28 |
Apache POI를 사용하여 Excel에서 셀 병합 (0) | 2020.12.28 |