当我按照本指南尝试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_populates
或backref
?我什么时候该用一个还是另一个?
如果使用
backref
,则不需要在第二个表上声明关系。如果您不使用
backref
,并且单独定义relationship
,那么如果您不使用back_populates
,sqlalchemy将不知道如何连接关系,因此修改一个也会修改另一个。因此,在您的示例中,您已经分别定义了
relationship
,但没有提供back_populates
参数,修改一个字段不会自动更新事务中的另一个字段。看看它怎么没有自动填写
children
字段?现在,如果您提供一个
back_populates
参数,sqlalchemy将连接这些字段。所以现在我们得到
Sqlalchemy知道这两个字段现在是相关的,并且会随着另一个字段的更新而更新。值得注意的是,使用
backref
也可以做到这一点。如果您想定义每个类上的关系,那么使用back_populates
是很好的,因此很容易看到所有的字段只是浏览模型类,而不必查看通过backref定义字段的其他类。相关问题 更多 >
编程相关推荐