﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
31634	Add support for With clause	Ryan Heard	nobody	"Multiple database providers including [https://www.postgresql.org/docs/9.1/queries-with.html PostgreSQL], [https://dev.mysql.com/doc/refman/8.0/en/with.html MySQL] and [https://oracle-base.com/articles/misc/with-clause Oracle] provide a WITH clause which can eliminate duplicate operations by putting results into a variable which can be reused.

To add this to the Django ORM, I propose adding a {{{with_clause}}} method to {{{QuerySet}}}. Note that {{{with}}} is a defined keyword and cannot be used. 

To imagine how this might work, we can look at the example found in the PostgreSQL documentation and try to rebuild it using the Django ORM
{{{
Orders.objects.with_clause(
    regional_sales=Orders.objects.values('region').distinct().annotate(total_sales=Sum('amount')),
    top_regions=F('regional_sales').values('region').filter(total_sales__gt=Sum('total_sales')),
).filter(
    region__in=F('top_regions'),
).values(
    'region', 'product',
).distinct().annotate(
    product_units=Sum('quantity'),
    product_sales=Sum('amount'),
)
}}}"	New feature	closed	Uncategorized	dev	Normal	duplicate			Unreviewed	0	0	0	0	0	0
