How to initialize backrefs of mappers without some queries through a session?
For example, I have two models, named "Client" and "Subject" in follow code:
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'))
Then, somewhere in my code, I want to get the backref client
of the class Subject
like this, but that raises an exception:
>>> Subject.client
AttributeError: type object 'Subject' has no attribute 'client'
After a query to Client
like:
>>> session.query(Client).first()
>>> Subject.client
<sqlalchemy.orm.attributes.InstrumentedAttribute at 0x43ca1d0>
Attribute client
was created after a query to the related model(mapper).
I don't want to make such "warming" queries!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…