2015-10-19 67 views
0

我有兩個表,並且定義了一個一對多的關係。與sqlalchemy的關係的動態行爲

from sqlalchemy import Column, Integer, ForeignKey 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import relationship 

Base = declarative_base() 


class Parent(Base): 
    __tablename__ = 'parent' 
    id = Column(Integer, primary_key=True) 
    children = relationship("Child", backref="parent") 


class Child(Base): 
    __tablename__ = 'child' 
    id = Column(Integer, primary_key=True) 
    parent_id = Column(Integer, ForeignKey('parent.id')) 

如果我嘗試訪問Child.parent,我得到一個錯誤。 但是,如果我初始化一個孩子的實例錯誤消失。

我想初始化一個Child實例修改Child類,但我不明白如何。 如何在不創建Child實例的情況下訪問Child.parent?

In [1]: Child.parent 
--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-2-8b757eeb36c4> in <module>() 
----> 1 Child.parent 

AttributeError: type object 'Child' has no attribute 'parent' 

In [2]: Child() 
Out[2]: <etl.es_utils.test_to_rm.Child at 0x7f38caf42c50> 

In [3]: Child.parent 

回答

0

而不是使用backref,我定義關係在雙方,它解決了這個問題。

from sqlalchemy import Column, Integer, ForeignKey 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import relationship 

Base = declarative_base() 


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")