Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Django natively support common table expressions?

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.

like image 364
Hoa Avatar asked Jul 06 '13 01:07

Hoa


People also ask

What are the two types of common table expression supported by SQL Server?

You can also use a CTE in a CREATE VIEW statement, as part of the view's SELECT query. In addition, as of SQL Server 2008, you can add a CTE to the new MERGE statement. This article covers SQL Server common tables expression (CTE) basics. SQL Server supports two types of CTEs-recursive and nonrecursive.

Why would you use a common table expression?

CTEs, like database views and derived tables, enable users to more easily write and maintain complex queries via increased readability and simplification. This reduction in complexity is achieved by deconstructing ordinarily complex queries into simple blocks to be used, and reused if necessary, in rewriting the query.

Can I use a common table expression in a view?

CTE was introduced in SQL Server 2005, the common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. You can also use a CTE in a CREATE a view, as part of the view's SELECT query.

What is a QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

Django doesn't support CTEs directly as these are not common to all databases (MySQL doesn't support it). There are packages that extend the capability of Django's ORM to support CTEs. One of these is django-cte-trees. Note that it only supports PostgreSQL.

like image 51
CadentOrange Avatar answered Oct 15 '22 07:10

CadentOrange