Flatten search registry to register by app_label.model_name

This commit is contained in:
jeremystretch 2022-10-21 09:13:24 -04:00
parent d713915a85
commit 7ebffa85f7
4 changed files with 14 additions and 20 deletions

View File

@ -21,8 +21,7 @@ class Command(BaseCommand):
# No models specified; pull in all registered indexers
if not model_names:
for app_label, models in registry['search'].items():
for _, idx in models.items():
for idx in registry['search'].values():
indexers[idx.model] = idx
# Return only indexers for the specified models
@ -35,10 +34,10 @@ class Command(BaseCommand):
f"Invalid model: {label}. Model names must be in the format <app_label>.<model_name>."
)
try:
idx = registry['search'][app_label][model_name]
idx = registry['search'][f'{app_label}.{model_name}']
indexers[idx.model] = idx
except KeyError:
raise CommandError(f"No indexer found for {label}")
raise CommandError(f"No indexer registered for {label}")
return indexers

View File

@ -29,5 +29,5 @@ registry['model_features'] = {
feature: collections.defaultdict(set) for feature in EXTRAS_FEATURES
}
registry['denormalized_fields'] = collections.defaultdict(list)
registry['search'] = collections.defaultdict(dict)
registry['search'] = dict()
registry['views'] = collections.defaultdict(dict)

View File

@ -97,22 +97,19 @@ class SearchIndex:
def get_indexer(model):
"""
Get the search indexer class for the given model.
Get the SearchIndex class for the given model.
"""
app_label = model._meta.app_label
model_name = model._meta.model_name
label = f'{model._meta.app_label}.{model._meta.model_name}'
return registry['search'][app_label][model_name]
return registry['search'][label]
def register_search(cls):
"""
Decorator for registering a SearchIndex with a particular model.
Decorator for registering a SearchIndex class.
"""
model = cls.model
app_label = model._meta.app_label
model_name = model._meta.model_name
registry['search'][app_label][model_name] = cls
label = f'{model._meta.app_label}.{model._meta.model_name}'
registry['search'][label] = cls
return cls

View File

@ -35,11 +35,9 @@ class SearchBackend:
# Organize choices by category
categories = defaultdict(dict)
for app_label, models in registry['search'].items():
for name, cls in models.items():
title = bettertitle(cls.model._meta.verbose_name)
value = f'{app_label}.{name}'
categories[cls.get_category()][value] = title
for label, idx in registry['search'].items():
title = bettertitle(idx.model._meta.verbose_name)
categories[idx.get_category()][label] = title
# Compile a nested tuple of choices for form rendering
results = (