2015-10-19 60 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")