1
0
mirror of https://github.com/django/django.git synced 2025-10-31 09:41:08 +00:00

Refs #26780 -- Made prefetch_related() don't use window expressions fo sliced queries if not supported.

This commit is contained in:
Mariusz Felisiak
2022-09-06 05:54:35 +02:00
committed by GitHub
parent 19e0587ee5
commit 69fa2e8eb2
2 changed files with 35 additions and 7 deletions

View File

@@ -64,7 +64,13 @@ and two directions (forward and reverse) for a total of six combinations.
"""
from django.core.exceptions import FieldError
from django.db import DEFAULT_DB_ALIAS, connections, router, transaction
from django.db import (
DEFAULT_DB_ALIAS,
NotSupportedError,
connections,
router,
transaction,
)
from django.db.models import Q, Window, signals
from django.db.models.functions import RowNumber
from django.db.models.lookups import GreaterThan, LessThanOrEqual
@@ -85,13 +91,16 @@ class ForeignKeyDeferredAttribute(DeferredAttribute):
def _filter_prefetch_queryset(queryset, field_name, instances):
predicate = Q(**{f"{field_name}__in": instances})
db = queryset._db or DEFAULT_DB_ALIAS
if queryset.query.is_sliced:
if not connections[db].features.supports_over_clause:
raise NotSupportedError(
"Prefetching from a limited queryset is only supported on backends "
"that support window functions."
)
low_mark, high_mark = queryset.query.low_mark, queryset.query.high_mark
order_by = [
expr
for expr, _ in queryset.query.get_compiler(
using=queryset._db or DEFAULT_DB_ALIAS
).get_order_by()
expr for expr, _ in queryset.query.get_compiler(using=db).get_order_by()
]
window = Window(RowNumber(), partition_by=field_name, order_by=order_by)
predicate &= GreaterThan(window, low_mark)