Ticket #35399: group_the_case-whens_into_sub-chunks_.patch

File group_the_case-whens_into_sub-chunks_.patch, 1.9 KB (added by Willem Van Onsem, 7 months ago)
  • django/db/models/query.py

    Subject: [PATCH] group the case-whens into sub-chunks.
    ---
    IDEA additional info:
    Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
    <+>UTF-8
    diff --git a/django/db/models/query.py b/django/db/models/query.py
    a b  
    55import copy
    66import operator
    77import warnings
     8from collections import defaultdict
    89from itertools import chain, islice
    910
    1011from asgiref.sync import sync_to_async
     
    907908            update_kwargs = {}
    908909            for field in fields:
    909910                when_statements = []
     911                chunks = defaultdict(list)
    910912                for obj in batch_objs:
    911913                    attr = getattr(obj, field.attname)
    912914                    if not hasattr(attr, "resolve_expression"):
    913915                        attr = Value(attr, output_field=field)
     916                    try:
     917                        if chunks is not None:
     918                            chunks[attr].append(obj.pk)
     919                    except TypeError:
     920                        # one value can not be hashed, so omit chunking
     921                        chunks = None
    914922                    when_statements.append(When(pk=obj.pk, then=attr))
    915                 case_statement = Case(*when_statements, output_field=field)
     923                if chunks is not None:  # all values were hashable
     924                    case_statement = Case(*[When(pk__in=pks, then=val) for val, pks in chunks.items()], output_field=field)
     925                else:
     926                    case_statement = Case(*when_statements, output_field=field)
    916927                if requires_casting:
    917928                    case_statement = Cast(case_statement, output_field=field)
    918929                update_kwargs[field.attname] = case_statement
Back to Top