如何在Sqlalchemy中使用条件配置多对多 [英] How to config Many-to-many with condition, in Sqlalchemy

查看:479
本文介绍了如何在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?

推荐答案

您可以通过在secondaryjoin参数替换SQLAlchemy的默认条件,从而对联接施加额外条件. org/docs/reference/orm/mapping.html#sqlalchemy.orm.relationship"rel =" noreferrer> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆