Opened 4 years ago

Closed 4 years ago

#31634 closed New feature (duplicate)

Add support for With clause

Reported by: Ryan Heard Owned by: nobody
Component: Uncategorized Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Multiple database providers including PostgreSQL, MySQL and 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'),
)

Change History (1)

comment:1 by Simon Charette, 4 years ago

Resolution: duplicate
Status: newclosed

Duplicate of #28919.

Note: See TracTickets for help on using tickets.
Back to Top