How to config Many-to-many with condition, in Sqlalchemy

后端 未结 1 795
盖世英雄少女心
盖世英雄少女心 2021-01-16 08:44

I\'m use sqlalchemy 0.6.4.

I have 2 classes: Question and Tag, they are many-to-many.

class Question(Base):
    __tablename__ = \"questions\"

    id         


        
相关标签:
1条回答
  • 2021-01-16 09:29

    You can impose extra conditions on the join by replacing SQLAlchemy's default condition via the secondaryjoin parameter to relationship. Since you're replacing the default (not just adding to it), you'll need to manually re-specify the original condition along with the new one:

    from sqlalchemy import sql
    
    # ...
    
    class Tag(Base):
        __tablename__ = "tags"
    
        id = Column(BigInteger, primary_key=True)
    
        questions = relationship('Question',
            secondary=r_questions_tags,
            secondaryjoin=sql.and_(
                r_questions_tags.c.question_id == Question.id,
                Question.deleted == False))
    
        deleted_questions = relationship('Question',
            secondary=r_questions_tags,
            secondaryjoin=sql.and_(
                r_questions_tags.c.question_id == Question.id,
                Question.deleted == True))
    
    0 讨论(0)
提交回复
热议问题