【问题标题】:How to reference the child of a many to one relationship in SQLAlchemy?如何在 SQLAlchemy 中引用多对一关系的孩子?
【发布时间】:2011-10-29 03:33:52
【问题描述】:

使用文档中的示例,我有以下代码。当我尝试追加时,我收到错误:

AttributeError: 'NoneType' object has no attribute 'append'    

显然,即使不使用appendparent.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)

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    您设置了多对一关系,这样父母可以有一个孩子,而孩子可以有多个父母。如果这是您的意图,您可以像这样设置孩子:

    parent.child = child
    

    然而,一个孩子可以像这样添加一个父母:

    child.parents.append(parent)
    

    如果这不是您想要的,您将不得不切换关系,以便父母可以通过设置多对多关系或将多对一的方向切换来拥有多个孩子。

    【讨论】:

    • 谢谢,是的,多对一正是我想要的。现在就试试吧。
    猜你喜欢
    • 2012-02-08
    • 2014-03-12
    • 1970-01-01
    • 2021-08-14
    • 2018-05-03
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    相关资源
    最近更新 更多