Skip to content

Commit a83925e

Browse files
authored
Disambiguate cache key for similarly named models (#140)
* Disambiguate cache key for similarly named models Two models with the same name in different apps would previously get the same cache key. Including the model's module in the cache key fixes this.
1 parent e516666 commit a83925e

File tree

6 files changed

+21
-1
lines changed

6 files changed

+21
-1
lines changed

CHANGES

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
Unreleased
22
==========
33

4+
* Fix similarly named models from different apps having the same cache key
5+
46
django-solo-2.3.0
57
=================
68

solo/models.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ def set_to_cache(self) -> None:
6464
@classmethod
6565
def get_cache_key(cls) -> str:
6666
prefix = getattr(settings, "SOLO_CACHE_PREFIX", solo_settings.SOLO_CACHE_PREFIX)
67-
return f"{prefix}:{cls.__name__.lower()}"
67+
# Include the model's module in the cache key so similarly named models from different
68+
# apps do not have the same cache key.
69+
return f"{prefix}:{cls.__module__.lower()}:{cls.__name__.lower()}"
6870

6971
@classmethod
7072
def get_solo(cls) -> Self:

solo/tests/settings.py

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
INSTALLED_APPS = (
1818
"solo",
1919
"solo.tests",
20+
"solo.tests.testapp2",
2021
)
2122

2223
SECRET_KEY = "any-key"

solo/tests/testapp2/__init__.py

Whitespace-only changes.

solo/tests/testapp2/models.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from solo.models import SingletonModel
2+
3+
4+
class SiteConfiguration(SingletonModel):
5+
class Meta:
6+
verbose_name = "Site Configuration 2"

solo/tests/tests.py

+9
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from django.test.utils import override_settings
66

77
from solo.tests.models import SiteConfiguration, SiteConfigurationWithExplicitlyGivenId
8+
from solo.tests.testapp2.models import SiteConfiguration as SiteConfiguration2
89

910

1011
class SingletonTest(TestCase):
@@ -103,3 +104,11 @@ def setUp(self):
103104
def test_when_singleton_instance_id_is_given_created_item_will_have_given_instance_id(self):
104105
item = SiteConfigurationWithExplicitlyGivenId.get_solo()
105106
self.assertEqual(item.pk, SiteConfigurationWithExplicitlyGivenId.singleton_instance_id)
107+
108+
109+
class SingletonsWithAmbiguousNameTest(TestCase):
110+
def test_cache_key_is_not_ambiguous(self):
111+
assert SiteConfiguration.get_cache_key() != SiteConfiguration2.get_cache_key()
112+
113+
def test_get_solo_returns_the_correct_singleton(self):
114+
assert SiteConfiguration.get_solo() != SiteConfiguration2.get_solo()

0 commit comments

Comments
 (0)