﻿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
35559	Calling list() on an empty sliced union still causes a database query	Lucidiot	Simon Charette	"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."	Cleanup/optimization	closed	Database layer (models, ORM)	5.0	Normal	fixed			Ready for checkin	1	0	0	0	0	0
