当我尝试按照本指南进行SQLAlchemy Relation Example时:基本关系模式
我有这个代码
#!/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
在我的示例中?什么时候应该使用其中一个?
back_populates
vsbackref
:的注释backref
更为简洁,因为您不需要在两个类上都声明该关系,但是实际上,我发现不值得在线保存该关系。我认为back_populates
更好,不仅因为在python文化中,“显式比隐式更好”(Python的Zen),而且当您有许多模型时,快速浏览一下它的声明,就可以看到所有关系及其名称,而不必翻阅所有相关模型。另外,一个不错的附带好处back_populates
是,您可以在大多数IDE上双向实现自动完成=)