Opened 8 years ago

Last modified 21 months ago

#27412 closed New feature

Coalesce function should work with subqueries — at Version 2

Reported by: Tzu-ping Chung Owned by: nobody
Component: Database layer (models, ORM) Version: 1.10
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Tzu-ping Chung)

Say I have a model

class Foo(models.Model):
    val = models.IntegerField()

with data 1, 2, 3, 4, 5. In SQL I can do (roughly)

SELECT val FROM foo WHERE val >= COALESCE((SELECT val FROM foo WHERE val=6 LIMIT 1 OFFSET 0), 3);

to get 3, 4, and 5. Translated into Django ORM query language:

Foo.objects.filter(val__gte=Coalesce(Foo.objects.filter(val=6).values_list('val', flat=True)[:1], 3))

I get a ProgrammingError because Django does not handle subqueries, and passes the QuerySet object directly to the SQL backend.

The reason I don’t want to use first() instead is that I am doing some query-joining in a loop, and repeated first() calls result in lots of queries, dragging the database down.

Change History (2)

comment:1 by Tim Graham, 8 years ago

Triage Stage: UnreviewedAccepted

comment:2 by Tzu-ping Chung, 8 years ago

Description: modified (diff)
Summary: Coalesce function does not work with subqueriesCoalesce function should work with subqueries
Note: See TracTickets for help on using tickets.
Back to Top