Sqlalchemy使用棉花糖返回带有嵌套连接的关系

时间:2019-05-21 16:04:54

标签: sqlalchemy flask-sqlalchemy marshmallow

目前,我有一堆表,它们之间建立了明确的关系。但是,我希望与答案表和问题表有关系的一个表(应用程序)仅显示具有标记为活动的问题的答案。我正在尝试通过应用程序模型执行此操作,以便在棉花糖中它可以返回到应用程序内部。我也正在尝试不产生N + 1查询的情况。

表格

application_question_table = db.Table(
    'application_questions',
    db.Column(
        'application_id',
        db.Integer,
        db.ForeignKey(
            'application.id',
            name="application_questions_application_id_fkey",
            ondelete="CASCADE"
        )
    ),
    db.Column(
        'question_id',
        db.Integer,
    db.ForeignKey(
            'question.id', 
            name="application_questions_question_id_fkey",
            ondelete="CASCADE"
        )
    )
)

class Application(Base):
    id = db.Column(db.Integer, primary_key=True)
    answers = db.relationship('Answer', back_populates="application", cascade=‘delete)
    active_answers = db.relationship("should only show answerswhere question is active")
    questions = db.relationship('Question', lazy="dynamic", secondary=application_question_table)


class Answer(Base):
    id = db.Column(db.Integer, primary_key=True)
    question_id = db.Column(db.Integer, db.ForeignKey('question.id', ondelete="SET NULL", name="answer_question_id_fkey"))
    question = db.relationship('Question', back_populates=“answers")


class Question(Base):
    id = db.Column(db.Integer, primary_key=True)
    answers = db.relationship("Answer", back_populates="question")
    applications = db.relationship('Application',lazy="dynamic", secondary=application_question_table)
    active = db.Column(db.Boolean, default=True)

模式-请注意,获得可见问题本质上是我想发生的事情。但是我不喜欢这样,因为它将是我发现的每个应用程序的一个附加查询。

class ApplicationSchema(ModelSchema):
    visible_answers = fields.Method('get_visible_answers')
    class Meta:
        model = Application

    def get_visible_answers(self, application):
        schema = ApplicationAnswerSchema(many=True)
        answers = Answer.query.join(
            Answer.application,
            Answer.question
        ).filter(
            Application.id == application.id,
            Question.active == True,
        ).all()
        return schema.dump(answers).data


class ApplicationAnswerSchema(ModelSchema):

    class Meta:
        model = Answer

我的预期行为是当我做类似的事情

applications = Application.query.options(joinedload(Application.active_answers)).all()
schema = ApplicationSchema(many=True)
results = schema.dump(applications)

只有一个查询,我可以键入每个应用程序并获得可见的答案。

我得到的实际结果是,我要为每个应用程序发出一个附加查询。

0 个答案:

没有答案