SQLAlchemy:关系中的动态主连接

时间:2020-07-24 09:26:53

标签: sqlalchemy

我使用声明式方式。好吧,我有两个模型DBOffer和DBRespond

class DBOffer(BaseModel):
    __tablename__ = 'offers'

    created_at = Column(TIMESTAMP, nullable=False)
    updated_at = Column(TIMESTAMP, nullable=False)
    executor_uid = Column(Integer, ForeignKey('users_snapshot.id', ondelete='CASCADE'), nullable=True, index=True)
    uid = Column(Integer, ForeignKey('users_snapshot.id', ondelete='CASCADE'), nullable=False, index=True)
    respond = relationship(
       DBRespond, 
       uselist=False, 
       viewonly=True, 
       lazy='joined', 
       primaryjoin='and_(DBOffer.executor_uid == DBRespond.uid, DBOffer.id == DBRespond.oid)')
    ***

class DBRespond(BaseModel):
    __tablename__ = 'responds'

    oid = Column(Integer, ForeignKey('offers.id', ondelete='CASCADE'), nullable=False, index=True)
    ***

问题是当我执行查询时:

session.query(DBOffer).filter(DBOffer.id == oid)

我需要在运行时将DBOffer.respond的主联接从and_(DBOffer.executor_uid == DBRespond.uid, DBOffer.id == DBRespond.oid)更改为and_(uid == DBRespond.uid, DBOffer.id == DBRespond.oid)(uid是用户id的参数)。

是否可以在运行时执行? 响应的primaryjoin取决于uid参数。如果请求要约的用户不是所有者,则他必须通过其ID进行响应。如果用户是要约的所有者,则必须让执行者响应。

0 个答案:

没有答案