Skip to content

Commit 8b71094

Browse files
committed
Cache custom field and value model
The models don't change in a running app.
1 parent 57acaf9 commit 8b71094

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

app/tests/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
from django.test import TransactionTestCase
55
from rest_framework.test import APIClient
66

7+
from django_features.custom_fields.helpers import clear_custom_field_model_cache
8+
79

810
User = get_user_model()
911

@@ -18,6 +20,10 @@ def setUp(self) -> None:
1820
self.login("kathi.barfuss")
1921
self.session = self.client.session
2022

23+
def tearDown(self) -> None:
24+
super().tearDown()
25+
clear_custom_field_model_cache()
26+
2127
def get_or_create_user(self, username: str) -> tuple[Any, bool]:
2228
user, created = User.objects.get_or_create(username=username)
2329
if created:

django_features/custom_fields/helpers.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,26 @@
1-
__all__ = ["get_custom_field_model", "get_custom_value_model"]
1+
__all__ = [
2+
"get_custom_field_model",
3+
"get_custom_value_model",
4+
"clear_custom_field_model_cache",
5+
]
26

37

8+
from functools import lru_cache
9+
410
from django.apps import apps as django_apps
511
from django.conf import settings
12+
from django.contrib.auth import get_user_model
613
from django.core.exceptions import ImproperlyConfigured
714

815
from django_features.custom_fields.models.field import AbstractBaseCustomField
916
from django_features.custom_fields.models.value import AbstractBaseCustomValue
1017

1118

12-
def get_custom_field_model() -> AbstractBaseCustomField:
19+
@lru_cache(maxsize=1)
20+
def get_custom_field_model() -> type[AbstractBaseCustomField]:
21+
22+
get_user_model()
23+
1324
"""
1425
Return the CustomField model that is active in this project.
1526
"""
@@ -31,7 +42,8 @@ def get_custom_field_model() -> AbstractBaseCustomField:
3142
)
3243

3344

34-
def get_custom_value_model() -> AbstractBaseCustomValue:
45+
@lru_cache(maxsize=1)
46+
def get_custom_value_model() -> type[AbstractBaseCustomValue]:
3547
"""
3648
Return the CustomValue model that is active in this project.
3749
"""
@@ -53,3 +65,11 @@ def get_custom_value_model() -> AbstractBaseCustomValue:
5365
"CUSTOM_FIELD_VALUE_MODEL refers to model '%s' that has not been installed"
5466
% settings.CUSTOM_FIELD_VALUE_MODEL
5567
)
68+
69+
70+
def clear_custom_field_model_cache() -> None:
71+
"""
72+
Clear cached model lookups for custom fields.
73+
"""
74+
get_custom_field_model.cache_clear()
75+
get_custom_value_model.cache_clear()

0 commit comments

Comments
 (0)