sqlalchemy의 다 대다 쿼리

Oct 16 2020

내 질문에 대한 테이블이 있습니다.

class TemplateExtra(ExtraBase, InsertMixin, TimestampMixin):
    __tablename__ = 'template_extra'

    id = Column(Integer, primary_key=True, autoincrement=False)
    name = Column(Text, nullable=False)
    roles = relationship(
        'RecipientRoleExtra',
        secondary='template_to_role',
    )


class RecipientRoleExtra(
    ExtraBase, InsertMixin, TimestampMixin,
    SelectMixin, UpdateMixin,
):
    __tablename__ = 'recipient_role'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(Text, nullable=False)
    description = Column(Text, nullable=False)


class TemplateToRecipientRoleExtra(ExtraBase, InsertMixin, TimestampMixin):
    __tablename__ = 'template_to_role'

    id = Column(Integer, primary_key=True, autoincrement=True)
    template_id = Column(Integer, ForeignKey('template_extra.id'))
    role_id = Column(Integer, ForeignKey('recipient_role.id'))

Django ORM이 prefetch_related로 수행하는 것과 같은 두 개의 SQL 쿼리에서 프리 페치 된 역할이있는 모든 템플릿을 선택하고 싶습니다. 할 수 있습니까? 이것이 나의 현재 시도입니다.

def test_custom():
    # creating engine with echo=True
    s = DBSession()

    for t in s.query(TemplateExtra).join(RecipientRoleExtra, TemplateExtra.roles).all():
        print(f'id = {t.id}')
        for r in t.roles:
            print(f'-- {r.name}')

그러나..

  1. 모든 템플릿에 대한 선택 쿼리를 생성하여 역할을 선택합니다. 하나의 쿼리 만 수행하도록 sqlalchemy를 만들 수 있습니까?
  2. 역할에 대한 생성 쿼리없이 그냥 가입하고 있습니다 FROM recipient_role, template_to_roleWHERE %(param_1)s = template_to_role.template_id AND recipient_role.id = template_to_role.role_id. 맞습니까?

나를 도와 주실 수있으세요?

답변

1 ky_aaaa Oct 16 2020 at 21:46

이 답변을 기반으로 : django의 prefetch_related에 의해 수행되는 플라스크 다 대다 조인

아마도 다음과 같을 것입니다.

roles = TemplateExtra.query.options(db.joinedload(TemplateExtra.roles)).all

효과가 있는지 알려주세요.