如何在SQLAlchemy中引用多对一关系的子项?
根据文档中的例子,我写了以下代码。当我尝试添加内容时,出现了错误:
AttributeError: 'NoneType' object has no attribute 'append'
显然,即使不使用 append
,parent.child
的类型也是 NoneType。我不知道该如何处理这种关系。
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'))
child = relationship("Child", backref="parents")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine("mysql://localhost/test", echo=False)
Session = sessionmaker(bind=engine)
session = Session()
metadata = Base.metadata
metadata.drop_all(engine)
metadata.create_all(engine)
parent = Parent()
child = Child()
parent.child.append(child)
1 个回答
2
你设置了一个“多对一”的关系,这样一个父母可以有一个孩子,而一个孩子可以有多个父母。如果你是这样想的,你可以像下面这样设置孩子:
parent.child = child
不过,一个孩子也可以像下面这样添加一个父母:
child.parents.append(parent)
如果这不是你想要的关系,那你就需要调整一下,把关系改成“多对多”,这样父母就可以有多个孩子,或者把“多对一”的方向反过来。