如何使用SQLAlchemy强制创建backref InstrumentedAttributes

时间:2015-09-16 19:45:11

标签: python orm sqlalchemy

在下面的示例中,我希望能够强制在parent类上创建Child属性。目前,在访问定义关系的Parent类的RelationshipProperty属性之前,不会创建它。

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, ForeignKey
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
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Child' has no attribute 'parent'
>>> Parent.children.property
<RelationshipProperty at 0x3dc3b00; children>
>>> Child.parent
<sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x0000000004718F60>

2 个答案:

答案 0 :(得分:1)

您希望能够在<{em} Parent课程中为Child班级定义backref。 SQLAlchemy显然没有一个非常简化的语法来实现这一点,但我相信以下内容将起作用:

class Parent(base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship(Child, order_by=Child.id, backref='child')

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

我希望这有用。

答案 1 :(得分:1)

Citing西蒙金:

  

如果您想触发所有&#34;待定&#34; backref   属性,我想你可以打电话   sqlalchemy.orm.configure_mappers

     

通常,当您开始查询时会自动调用此方法   数据库,但在某些情况下,您可能希望明确地调用它。