2011-10-28 62 views
0

使用示例關閉文檔,我有以下代碼。當我嘗試添加我得到的錯誤:如何在SQLAlchemy中引用多對一關係的子對象?

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) 

回答

2

您建立了多對一的關係,以便父母可以有一個孩子,孩子可以有很多父母。如果這是你如何打算,你可以設置孩子,像這樣:

parent.child = child 

一個孩子,但是,可以添加一個家長像這樣:

child.parents.append(parent) 

如果這不是你如何打算,您必須切換關係,以便父母可以通過設置多對多關係或通過將多方關係切換爲一對多來關聯多個孩子。

+0

謝謝,是的,多對一正是我想要的。現在嘗試。 – esac

相關問題