【问题标题】:Query on many-to-many relationship in sqlalchemy在 sqlalchemy 中查询多对多关系
【发布时间】:2019-08-03 21:38:20
【问题描述】:

我有两个通过关系表链接的数据库类,我可以检索分配给每篇论文的问题。但是,我想检索当前分配给当前论文的所有问题,而不管它们分配给的任何其他论文。我尝试了很多不同的东西,但都没有达到我想要的效果。

我相信某种外部左连接应该可以做到这一点,但我无法弄清楚正确的语法。

提前感谢您的建议。

这是目前的数据库结构:

class Question(db.Model):
    __tablename__ = 'question'
    id = db.Column(db.Integer, primary_key=True)
    papers = db.relationship(
            'Paper', secondary='question_in', backref='has_question', lazy='dynamic')

class Paper(db.Model):
    __tablename__ = 'paper'
    id = db.Column(db.Integer, primary_key=True)
    #returns the questions in the paper
    def all_questions(self):
        questions = Question.query.filter(Question.papers.any(id=self.id)).all()
        return questions

Question_in = db.Table('question_in',
    db.Column('question_id', db.Integer, db.ForeignKey('question.id'), primary_key=True),
    db.Column('paper_id', db.Integer,db.ForeignKey('paper.id'), primary_key=True), 
)

【问题讨论】:

    标签: sql database flask sqlalchemy


    【解决方案1】:

    您应该能够遵循您在 all_questions 函数中使用的相同逻辑,并使用 subquery() 将其过滤掉:

    def not_assigned(self):
        assigned_questions = db.session.query(Question.id)\
                            .filter(Question.papers.any(id=self.id)).subquery()
        not_assigned = db.session.query(Question)\
                            .filter(Question.id.notin_(assigned_questions)).all()
        return not_assigned
    

    【讨论】:

    • 非常感谢您!这么简单的解决方案我就是看不到。
    猜你喜欢
    • 2011-09-26
    • 2019-01-18
    • 1970-01-01
    • 2018-02-24
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多