﻿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
36707	"Prefetch related query throwing ""Expression tree is too large"" error after updating to Django 5.2 when using sqlite3 DB"	Alexandru Chirila		"After updating to version 5.2.7 from 4.2.15 of Django some queries with prefetch related that used to work with the sqlite3 engine no longer work and are throwing the ""Expression tree is too large"" error.

-----

Example working with 4.2:

{{{
In [1]: import django

In [2]: django.__version__
Out[2]: '4.2.15'

In [3]: from dv.models import Organisation

In [4]: x = list(Organisation.objects.all().prefetch_related(""roles__project""))

In [5]: len(x)
Out[5]: 22321
}}}

----

Example working in 5.2 **without** prefetch

{{{
In [1]: import django

In [2]: django.__version__
Out[2]: '5.2.7'

In [3]: from dv.models import Organisation

In [4]: x = list(Organisation.objects.all())

In [5]: len(x)
Out[5]: 22321
}}}

--- 

Example of it not working with prefetch:

{{{
In [1]: import django

In [2]: django.__version__
Out[2]: '5.2.7'

In [3]: from dv.models import Organisation

In [4]: x = list(Organisation.objects.all().prefetch_related(""roles__project""))
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
File ~/PycharmProjects/dataviz/.venv/lib/python3.12/site-packages/django/db/backends/utils.py:105, in CursorWrapper._execute(self, sql, params, *ignored_wrapper_args)
    104 else:
--> 105     return self.cursor.execute(sql, params)

File ~/PycharmProjects/dataviz/.venv/lib/python3.12/site-packages/django/db/backends/sqlite3/base.py:360, in SQLiteCursorWrapper.execute(self, query, params)
    359 query = self.convert_query(query, param_names=param_names)
--> 360 return super().execute(query, params)

OperationalError: Expression tree is too large (maximum depth 1000)

}}}

"	Bug	closed	Database layer (models, ORM)	5.2	Normal	worksforme			Unreviewed	0	0	0	0	0	0
