#35559: Calling list() on an empty sliced union still causes a database query
-------------------------------------+-------------------------------------
               Reporter:  Lucidiot   |          Owner:  nobody
                   Type:  Bug        |         Status:  new
              Component:  Database   |        Version:  5.0
  layer (models, ORM)                |
               Severity:  Normal     |       Keywords:
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 When upgrading from Django 4.1 to 4.2, some of our unit tests failed
 because of unexpected SQL queries, and those queries are still present in
 Django 5.0.

 We have a Django REST Framework API view, which relies on Django's
 `Paginator` to do its pagination. It uses a `QuerySet` which involves a
 `UNION` of two other queries that both have some filters. Those filters
 can cause the whole union to be empty. The `Paginator` knows that the
 result count is 0, so it returns a page of results by slicing with
 `[0:0]`.

 In Django 4.1, calling `list()` on that sliced union would cause no query
 and an empty list is returned, but starting with 4.2, a query runs:

 {{{#!python
 qs = Thing.objects.filter(id__in=Thing.objects.none())
 list(qs)                 # 0 queries
 list(qs[0:0])            # 0 queries
 list(qs.union(qs))       # 0 queries
 list(qs.union(qs)[0:0])  # 1 query
 }}}

 {{{#!sql
 (
     SELECT "app_thing"."id" AS "col1"
     FROM "app_thing"
     WHERE 0 = 1
 ) UNION (
     SELECT "app_thing"."id" AS "col1"
     FROM "app_thing"
     WHERE 0 = 1
 )
 }}}

 I think this extra query was added in the fix for #34125.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35559>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/010701904ef45cf3-7234a5f4-62f4-445e-9a8b-d0d3788a8a34-000000%40eu-central-1.amazonses.com.

Reply via email to