セッションを介してクエリを実行せずにマッパーのバックリファレンスを初期化するにはどうすればよいですか?たとえば、次のコードに「Client」と「Subject」という名前の2つのモデルがあります。
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
次に、コードのどこかで、このようなクラスのバックリファレンスを取得したいのです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
は、関連するモデル(マッパー)へのクエリの後に作成されました。
私はそのような「暖かい」クエリをしたくありません!