如何在不通过会话进行一些查询的情况下初始化映射器的反向引用?例如,我有两个模型,分别在以下代码中命名为“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'))
然后,在我的代码中的某个地方,我想像这样获取client
类的 backref Subject
,但这会引发异常:
>>> Subject.client
AttributeError: type object 'Subject' has no attribute 'client'
查询后点Client
赞:
>>> session.query(Client).first()
>>> Subject.client
<sqlalchemy.orm.attributes.InstrumentedAttribute at 0x43ca1d0>
属性client
是在查询相关模型(映射器)后创建的。
我不想做这样的“温暖”查询!