我有四个表/类:GroupBankQuestionSurvey。调查有很多问题,问题属于银行,银行又属于一个组。我有小组和调查(我正在使用Survey的实例方法,并且正在遍历所有Group实例),并且想知道哪些问题属于这两个问题。

class Group(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    banks = db.relationship('Bank', backref='group')


class Bank(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    group_id = db.Column(db.Integer, db.ForeignKey('group.id')
    questions = db.relationship('Question', backref='bank', lazy='dynamic')


class Question(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    survey_id = db.Column(db.Integer, db.ForeignKey('survey.id')
    bank_id = db.Column(db.Integer, db.ForeignKey('bank.id')


class Survey(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    questions = db.relationship('Question', backref='survey', lazy='dynamic')


我想尝试尝试类似self.questions.filter(Question.bank.in_(group.banks))selfSurvey实例)的方法,但是得到了NotImplementedError。现在,我正在使用带有for条件的丑陋嵌套if循环,并试图对其进行清理,尤其是因为我预计随着调查和问题数量的增加,速度会出现问题。

for group in groups:
    for bank in group.banks:
      for question in bank.questions:
          if question in self.questions:
              # do stuff

最佳答案

您可以使用joins遍历关系以获取所需的信息。

此查询将调查表与他们共享的外部问题ID密钥上的银行表相连,然后将银行表与组表相连。

q = (session.query(Survey.id, Question.id, Group.id)
            .join(Survey.questions, Bank)
            .join(Group)
            .filter(Survey.id == self.id)
            .all())


要在一个查询中获取所有调查的信息,请删除filter子句。

查询生成的SQL是

SELECT survey.id AS survey_id, question.id AS question_id, "group".id AS group_id
    FROM survey
        JOIN question ON survey.id = question.survey_id
        JOIN bank ON bank.id = question.bank_id
        JOIN "group" ON "group".id = bank.group_id
    WHERE survey.id = ?

关于python - 如何获得与SQLAlchemy分开多个关系的匹配记录?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56178266/

10-16 12:58