From c21ea01528d620f43def86afed067e3586afc511 Mon Sep 17 00:00:00 2001 From: Chris Ramacciotti Date: Fri, 19 Sep 2025 22:54:40 -0500 Subject: [PATCH] Respects database prefix when removing stale keys --- constance/management/commands/constance.py | 3 ++- tests/test_cli.py | 23 ++++++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/constance/management/commands/constance.py b/constance/management/commands/constance.py index 289b459..60ae6e4 100644 --- a/constance/management/commands/constance.py +++ b/constance/management/commands/constance.py @@ -70,7 +70,8 @@ class Command(BaseCommand): for k, v in get_values().items(): self.stdout.write(f'{k}\t{v}', ending='\n') elif command == self.REMOVE_STALE_KEYS: - actual_keys = settings.CONSTANCE_CONFIG.keys() + prefix = getattr(settings, 'CONSTANCE_DATABASE_PREFIX', '') + actual_keys = [f'{prefix}{key}' for key in settings.CONSTANCE_CONFIG] stale_records = Constance.objects.exclude(key__in=actual_keys) if stale_records: self.stdout.write('The following record will be deleted:', ending='\n') diff --git a/tests/test_cli.py b/tests/test_cli.py index 68d8daf..960a8ef 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -6,11 +6,10 @@ from textwrap import dedent from django.conf import settings from django.core.management import CommandError from django.core.management import call_command -from django.test import TransactionTestCase +from django.test import TransactionTestCase, override_settings from django.utils import timezone from django.utils.encoding import smart_str -from constance import config from constance.models import Constance @@ -111,9 +110,29 @@ class CliTestCase(TransactionTestCase): ) def test_delete_stale_records(self): + self._populate_database_with_default_values() initial_count = Constance.objects.count() Constance.objects.create(key='STALE_KEY', value=None) call_command('constance', 'remove_stale_keys', stdout=self.out) self.assertEqual(Constance.objects.count(), initial_count, msg=self.out) + + @override_settings( + CONSTANCE_DATABASE_PREFIX='constance:', + ) + def test_delete_stale_records_respects_prefix(self): + self._populate_database_with_default_values() + initial_count = Constance.objects.count() + + call_command('constance', 'remove_stale_keys', stdout=self.out) + + self.assertEqual(Constance.objects.count(), initial_count, msg=self.out) + + def _populate_database_with_default_values(self): + """ + Helper function to populate the database with default values defined + in settings since that's not done automatically at startup + """ + for key, (value, *_) in settings.CONSTANCE_CONFIG.items(): + Constance.objects.create(key=f'{getattr(settings, "CONSTANCE_DATABASE_PREFIX", "")}{key}', value=value)