Development Tip

언제 sqlalchemy back_populates를 사용해야합니까?

yourdevel 2020. 12. 29. 07:59
반응형

언제 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_populatessqlalchemy가 관계를 연결하는 것을 알지 못하므로 하나를 수정하면 다른 것도 수정됩니다.

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

반응형