繁体   English   中英

sqlalchemy 中的多对多查询

[英]Many to many query in 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 FROM recipient_role, template_to_role with WHERE %(param_1)s = template_to_role.template_id AND recipient_role.id = template_to_role.role_id 这是正确的吗?

你能帮我吗?

基于这个答案: flask many to many join as done by prefetch_related from django

也许是这样的:

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

让我知道它是否有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM