To clarify my question I would like to know if it is possible to idiomatically use the Django ORM whilst accessing CTE features. I imagine I could use CTE by writing raw SQL statements but the ability to use the ORM 'syntactic sugar' to bypass hand coding SQL statements was one of the original appeals of Django.
Asked
Active
Viewed 3,841 times
2 Answers
12
Django doesn't support CTEs directly as these are not common to all databases (MySQL pre-8.0 didn't support it). There are packages that extend the capability of Django's ORM to support CTEs. One of these is django-cte. Note that it only supports PostgreSQL.

CadentOrange
- 3,263
- 1
- 34
- 52
-
4MySQL does now support CTEs, as does SQLite, Oracle, and PostgreSQL. All of which Django supports. – Bobort Nov 29 '17 at 19:59
-
1If someone is wondering: _django-cte-forest_ is a fork of _django-cte-trees_. – jnns Sep 16 '22 at 07:45
2
It seems that nowadays django-cte is a better option. It works with the existing support for CTEs in underlying database engines.

smido
- 771
- 6
- 14