Do not delete all search indexes when reindexing specific models

* Clear all indexes only if neither --lazy nor a list of models are
  specified for "manage.py reindex"

* Otherwise, clear the index for a model immediately before rebuilding
  it
This commit is contained in:
Peter Eckel 2024-06-27 18:05:55 +00:00
parent c7dcded74f
commit 1144b2e27d

View File

@ -67,8 +67,8 @@ class Command(BaseCommand):
self.stdout.write(f'Reindexing {len(indexers)} models.') self.stdout.write(f'Reindexing {len(indexers)} models.')
# Clear all cached values for the specified models (if not being lazy) # Clear all cached values for the specified models (if not being lazy)
if not kwargs['lazy']: if not kwargs['lazy'] and not model_labels:
self.stdout.write('Clearing cached values... ', ending='') self.stdout.write('Clearing all cached values... ', ending='')
self.stdout.flush() self.stdout.flush()
deleted_count = search_backend.clear() deleted_count = search_backend.clear()
self.stdout.write(f'{deleted_count} entries deleted.') self.stdout.write(f'{deleted_count} entries deleted.')
@ -81,12 +81,19 @@ class Command(BaseCommand):
self.stdout.write(f' {app_label}.{model_name}... ', ending='') self.stdout.write(f' {app_label}.{model_name}... ', ending='')
self.stdout.flush() self.stdout.flush()
if kwargs['lazy']: content_type = ContentType.objects.get_for_model(model)
content_type = ContentType.objects.get_for_model(model) cached_count = search_backend.count(object_types=[content_type])
if cached_count := search_backend.count(object_types=[content_type]):
if cached_count:
if kwargs['lazy']:
self.stdout.write(f'Skipping (found {cached_count} existing).') self.stdout.write(f'Skipping (found {cached_count} existing).')
continue continue
if model_labels:
self.stdout.write(f'clearing {cached_count} cached values... ', ending='')
self.stdout.flush()
search_backend.clear(object_types=[content_type])
i = search_backend.cache(model.objects.iterator(), remove_existing=False) i = search_backend.cache(model.objects.iterator(), remove_existing=False)
if i: if i:
self.stdout.write(f'{i} entries cached.') self.stdout.write(f'{i} entries cached.')