backref class attribute



如何在不通过会话进行某些查询的情况下初始化映射器的backrefs?例如,我有两个模型,分别命名为"客户端"one_answers"主题",代码如下:

Base = declarative_base()
class Client(Base):
    __tablename__ = "clients"
    id = Column(Integer, primary_key=True)
    created = Column(DateTime, default=datetime.datetime.now)
    name = Column(String)
    subjects = relationship("Subject",  cascade="all,delete",
        backref=backref("client"))

class Subject(Base):
    __tablename__ = "subjects"
    id = Column(Integer, primary_key=True)
    client_id = Column(Integer, ForeignKey(Client.id, ondelete='CASCADE'))

然后,在我的代码中,我想像这样获得类Subject的backref client,但这引发了一个异常:

>>> Subject.client
AttributeError: type object 'Subject' has no attribute 'client'

查询Client后,如:

>>> session.query(Client).first()
>>> Subject.client
<sqlalchemy.orm.attributes.InstrumentedAttribute at 0x43ca1d0>

属性client是在对相关模型(映射器)进行查询后创建的
我不想提出这样"暖心"的问题!

或者,您可以使用:

from sqlalchemy.orm import configure_mappers
configure_mappers()

这样做的优点是,它可以在一步中为所有模型创建所有backrefs。

因为SQLAlchemy使用元类,所以在创建Client类的至少一个实例之前,在其他类上创建反向引用的代码不会运行。

补救方法很简单:创建一个Client()实例,然后再次丢弃它:

>>> Subject.client
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Subject' has no attribute 'client'
>>> Client()
<__main__.Client object at 0x104bdc690>
>>> Subject.client
<sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x104be9e10>

或者使用configure_mappers实用程序功能:

from sqlalchemy.orm import configure_mappers

扫描您的模型以查找此类引用并初始化它们。实际上,创建任何一个实例都会在后台调用此方法。

相关内容

最新更新