试图通过中间表过滤

时间:2016-02-17 03:23:52

标签: python postgresql sqlalchemy

我正在尝试进行此查询

subsidiaries = self.con.query(Subsidiary)\
                    .options(joinedload(Subsidiary.commerce)\
                             .joinedload(Commerce.commerce_tags))\
                    .filter(CommerceTag.tag_id == id)

但它没有用,所以要解释一下:

表之间的关系是:

Relationship

我只想获得所有具有特定标签的商家的所有子公司,我想与子公司一起拥有基类(我知道如果我使用Commerce会更容易),原因是因为我用下一种格式将它转换为json值:

"subsidiaries": [
    {
        "id": 1,
        "name": "some_name",
        "commerce": {
            "id": 1,
            "name": "Commerce Name"
        }
    }
]

好吧,我可以使用商业基础类进行查询,但我认为,在查询中执行此操作可能需要迭代商业来获取子公司。

我不想加载CommerceTag,但我在joinload中加载了它,因为它不适用于Join方法。

我需要一些帮助才能做到这一点:(

1 个答案:

答案 0 :(得分:0)

以这种方式尝试:

subsidiaries = session.query(Subsidiary)\
                .join(Subsidiary.commerce)\
                .join(Commerce.commerce_tags)\
                .filter(CommerceTag.id == id)

您的语句会生成如下查询:

SELECT subsidiary.id AS subsidiary_id, subsidiary....
FROM tag, subsidiary
LEFT OUTER JOIN commerce AS commerce_1 
    ON subsidiary.id = commerce_1.subsidiary_id
LEFT OUTER JOIN (
    tags_by_commerce AS tags_by_commerce_1
    JOIN tag AS tag_1 ON tag_1.id = tags_by_commerce_1.id_tag
) ON commerce_1.id = tags_by_commerce_1.id_commerce
WHERE tag.id = :id_1

所以标签过滤没有效果。

我提出的陈述产生了这个:

SELECT subsidiary.id AS subsidiary_id, subsidiary.name AS subsidiary_name
FROM subsidiary 
JOIN commerce ON subsidiary.id = commerce.subsidiary_id
JOIN tags_by_commerce AS tags_by_commerce_1 ON commerce.id = tags_by_commerce_1.id_commerce
JOIN tag ON tag.id = tags_by_commerce_1.id_tag
WHERE tag.id = :id_1