Skip to content

Commit 5cc7462

Browse files
sir-sigurdtimgraham
authored andcommitted
Refs #28459 -- Optimized ModelState instantiation.
1 parent 97cb3bd commit 5cc7462

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

django/db/models/base.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -370,15 +370,23 @@ def _default_manager(cls):
370370
return cls._meta.default_manager
371371

372372

373+
class ModelStateFieldsCacheDescriptor:
374+
def __get__(self, instance, cls=None):
375+
if instance is None:
376+
return self
377+
res = instance.fields_cache = {}
378+
return res
379+
380+
373381
class ModelState:
374382
"""Store model instance state."""
375-
def __init__(self, db=None):
376-
self.db = db
377-
# If true, uniqueness validation checks will consider this a new, as-yet-unsaved object.
378-
# Necessary for correct validation of new instances of objects with explicit (non-auto) PKs.
379-
# This impacts validation only; it has no effect on the actual save.
380-
self.adding = True
381-
self.fields_cache = {}
383+
db = None
384+
# If true, uniqueness validation checks will consider this a new, unsaved
385+
# object. Necessary for correct validation of new instances of objects with
386+
# explicit (non-auto) PKs. This impacts validation only; it has no effect
387+
# on the actual save.
388+
adding = True
389+
fields_cache = ModelStateFieldsCacheDescriptor()
382390

383391

384392
class Model(metaclass=ModelBase):

tests/model_regress/test_state.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from django.db.models.base import ModelState, ModelStateFieldsCacheDescriptor
2+
from django.test import SimpleTestCase
3+
4+
5+
class ModelStateTests(SimpleTestCase):
6+
7+
def test_fields_cache_descriptor(self):
8+
self.assertIsInstance(ModelState.fields_cache, ModelStateFieldsCacheDescriptor)

0 commit comments

Comments
 (0)