sqlalchemy中的多对多查询

亚历克斯

有我的问题的表。

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'))

我想在两个sql查询中选择所有具有预提取角色的模板,例如Django ORM对prefetch_related的选择。我可以做吗?这是我目前的尝试。

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_role使用即可WHERE %(param_1)s = template_to_role.template_id AND recipient_role.id = template_to_role.role_id这是对的吗?

你能帮我吗?

ky_aaaa

基于此答案:django的prefetch_related完成了多对多烧瓶

也许是这样的:

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

让我知道它是否有效。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章