How can SQLAlchemy association_proxy be used bi-directionally?

大城市里の小女人 提交于 2019-12-04 19:46:42
Collin Allen

Found my answer in this Google Groups discussion. Here's the relevant portion:

class DossierTarife(Base):
    __tablename__ = 'tarifer_dossier'
    IdDossier = Column(Integer, ForeignKey('dossier.IdDossier'), primary_key=True)
    IdAt = Column(Integer, ForeignKey('article_tarife.IdAt'), primary_key=True)

    dossier = relationship(Dossier, backref=backref("tarifer_dossier", cascade="all, delete-orphan"))
    article_tarife = relationship(ArticleTarife, backref=backref("tarifer_dossier"))

class Dossier(Base):
    __tablename__ = 'dossier'
    IdDossier = Column('IdDossier', Integer, primary_key=True)
   ...

class ArticleTarife(Base):
    __tablename__ = 'article_tarife'
    IdAt = Column('IdAt', Integer, primary_key=True)
   ...

Dossier.LesTar = association_proxy("tarifer_dossier", "article_tarife", creator=lambda art:DossierTarife(article_tarife=art))
ArticleTarife.LesTar = association_proxy("tarifer_dossier", "dossier", creator=lambda dos:DossierTarife(dossier=dos))

I assigned my association_proxy directly within the class definition rather than doing it after the fact as above, and that worked well, too.

Also very helpful was this SO answer describing how to properly delete Association Object rows:

user = relationship(User, backref=backref('user_to_groups', cascade='all, delete-orphan'))
group = relationship(Group, backref=backref('group_to_user', cascade='all, delete-orphan'))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!