Respects database prefix when removing stale keys

This commit is contained in:
Chris Ramacciotti 2025-09-19 22:54:40 -05:00
parent 6970708e05
commit c21ea01528
2 changed files with 23 additions and 3 deletions

View file

@ -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')

View file

@ -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)