SQLAlchemy,私有变量的字段

时间:2017-02-09 17:05:43

标签: sqlalchemy

我正在使用一个带有属性和setter装饰器的类。我想知道为什么我必须在下面的示例中引用私有变量名_child而不是child。访问_child时,我不应通过setter / getter间接访问child

下面的最小例子:

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

Base = declarative_base()

class Parent(Base):
    __tablename__ = 'parents'

    id = Column(Integer, primary_key=True)
    child = relationship('Child', back_populates='parent')
    child_id = Column(Integer,ForeignKey('child.id'))
    def __init__(self):
        self._child= Child()

    @property
    def child(self):
        return self._child

    @child.setter
    def child(self, child):
        print('child set')
        self._child= child

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

    parent = relationship('Parent', back_populates='child')

    def __init__(self):
        pass

if __name__ == '__main__':
    child = Child()
    parent = Parent()
    parent.child = child

这会引发以下错误: sqlalchemy.exc.InvalidRequestError: Mapper 'Mapper|Parent|parents' has no property 'child'

如果我更换

child = relationship('Child', back_populates='parent')
# and
parent = relationship('Parent', back_populates='child')

_child = relationship('Child', back_populates='parent')
# and
parent = relationship('Parent', back_populates='_child')

一切正常

1 个答案:

答案 0 :(得分:0)

您使用相同名称的child隐藏关系property。它就像你没有完全建立关系一样,因此back_populates="child"无法找到名为child的关系,因为它不存在。

仅凭您的例子判断,您根本不需要property