'Django ORM join a Raw Query

I want to join a fairly complex subquery to a Django ORM queryset:

The resulting query should be like:

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

The joined subquery in the left outer join clause is quite complex, it involves aggregating from a union from different tables, and I can not write it in the ORM. I tried writing it in the ORM, but I could not achieve the UNION on different tables.... so I want to join it as raw subquery, and annotate the quantity column.

Something like:

Product.objects.all().join("my complex raw subquery")

Is this possible in the Django ORM?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source