Django ORM 加入原始查询

Mar*_*ski 5 django django-orm

我想将一个相当复杂的子查询加入到 Django ORM 查询集中:

结果查询应该是这样的:

select id from webshop_product
left outer join (
    select product_id, count(extra_col) as quantity from (
        select product_id, col1 as extra_col from xyz where x = 123 and y = 456
        union
        select product_id, col2 as extra_col from abc where a = 234 and y = 534
     ) as t1
) as t2 on t2.product_id = webshop_product.id
Run Code Online (Sandbox Code Playgroud)

左外连接子句中的连接子查询非常复杂,它涉及从不同表的联合进行聚合,我无法将其写在ORM中。我尝试在 ORM 中编写它,但是我无法在不同的表上实现 UNION...所以我想将它作为原始子查询加入,并注释数量列。

就像是:

Product.objects.all().join("my complex raw subquery")
Run Code Online (Sandbox Code Playgroud)

这在 Django ORM 中可能吗?