与sqlalchemy关系的动态行为

时间:2015-10-19 17:19:16

标签: python python-2.7 sqlalchemy relationships

我有两个表,并且已经定义了一对多的关系。

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

1 个答案:

答案 0 :(得分: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")