如何在Sqlalchemy中使用条件配置多对多 [英] How to config Many-to-many with condition, in Sqlalchemy
问题描述
我正在使用sqlalchemy 0.6.4.
I'm use sqlalchemy 0.6.4.
我有2个班级:Question和Tag,它们是多对多的.
I have 2 classes: Question and Tag, they are many-to-many.
class Question(Base):
__tablename__ = "questions"
id = Column(Integer, primary_key=True)
deleted = Column(Boolean)
...
tags = relationship('Tag', secondary=r_questions_tags)
class Tag(Base):
__tablename__ = "tags"
id = Column(BigInteger, primary_key=True)
questions = relationship('Question', secondary=r_questions_tags)
因此,tag.questions
将获得所有属于标签的问题.
So, tag.questions
will get all the questions belong to a tag.
但是现在,由于Question
具有deleted
列,我希望这样做:
But now, since the Question
has a deleted
column, I hope to do like this:
class Tag(Base):
...
# get non-deleted questions
questions = relationship('Question', secondary=r_questions_tags,
condition='Question.deleted==False')
# get deleted questions
deleted_questions = relationship('Question', secondary=r_questions_tags,
condition='Question.deleted==True')
但是不幸的是,没有这样的condition
参数.我现在该怎么办?
But unfortunately, there is no such condition
parameter. What can I do now?
推荐答案
您可以通过在relationship
.由于您要替换默认值(而不仅仅是添加默认值),因此您需要手动重新指定原始条件以及新条件:
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))
这篇关于如何在Sqlalchemy中使用条件配置多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!