与 sqlalchemy 关系的动态行为

Dynamic behaviour of relationship with 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 class,但我不明白如何。 如何在不创建 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

我没有使用 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")