何时需要使用sqlalchemy back_populates?

2024-05-14 16:59:21 发布

您现在位置:Python中文网/ 问答频道 /正文

当我按照本指南尝试SQLAlchemy关系示例时: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?我什么时候该用一个还是另一个?


Tags: fromimportidchildtruebasesqlalchemysession
1条回答
网友
1楼 · 发布于 2024-05-14 16:59:21

如果使用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定义字段的其他类。

相关问题 更多 >

    热门问题