backref类属性

QBa*_*man 5 python sqlalchemy

如何在没有通过会话的某些查询的情况下初始化映射器的backref?例如,我有两个模型,在以下代码中命名为"Client"和"Subject":

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'))
Run Code Online (Sandbox Code Playgroud)

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

>>> Subject.client
AttributeError: type object 'Subject' has no attribute 'client'
Run Code Online (Sandbox Code Playgroud)

在查询后Client喜欢:

>>> session.query(Client).first()
>>> Subject.client
<sqlalchemy.orm.attributes.InstrumentedAttribute at 0x43ca1d0>
Run Code Online (Sandbox Code Playgroud)

client在查询相关模型(映射器)之后创建属性.
我不想做这样的"变暖"查询!

mtt*_*tth 7

或者,您可以使用:

from sqlalchemy.orm import configure_mappers

configure_mappers()
Run Code Online (Sandbox Code Playgroud)

这样做的好处是可以一步为所有模型创建所有背景.


Mar*_*ers 5

因为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>
Run Code Online (Sandbox Code Playgroud)

或使用configure_mappers效用函数:

from sqlalchemy.orm import configure_mappers
Run Code Online (Sandbox Code Playgroud)

扫描模型以获取此类参考并初始化它们.实际上,创建任何一个实例都会在引擎盖下调用此方法.