我什么时候需要使用sqlalchemy back_populates?

时间:2016-10-05 09:08:57

标签: python sqlalchemy

当我按照本指南尝试SQLAlchemy Relation Example时:Basic Relationship Patterns

我有这段代码

#!/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_populatesbackref?我什么时候应该使用其中一种?

1 个答案:

答案 0 :(得分:101)

如果您使用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就赢了知道连接关系,以便修改一个也会修改另一个关系。

因此,在您的示例中,您已单独定义relationship但未提供back_populates参数,修改一个字段不会自动更新事务中的另一个字段

>>> parent = Parent()
>>> child = Child()
>>> child.parent = parent
>>> print parent.children
[]

了解它是如何自动填写children字段的?

现在,如果您提供back_populates参数,sqlalchemy将连接这些字段。

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")

现在我们得到

>>> parent = Parent()
>>> child = Child()
>>> child.parent = parent
>>> print parent.children
[Child(...)]

Sqlalchemy知道这两个字段现在是相关的,并且会在另一个更新时更新每个字段。值得注意的是,使用backref也会这样做。如果要在每个类上定义关系,使用back_populates是很好的,因此很容易看到所有字段都只是看了一下模型类,而不必查看通过backref定义字段的其他类。 / p>