Opened 8 years ago

Last modified 2 years ago

#27412 closed New feature

Coalesce function does not work with subqueries — at Initial Version

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

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 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 (0)

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