command line to rebuild index

This commit is contained in:
smilerz
2021-04-11 19:07:50 -05:00
parent f87c963e28
commit fd24117c27
2 changed files with 33 additions and 3 deletions

View File

@ -0,0 +1,27 @@
from django.conf import settings
from django.contrib.postgres.search import SearchVector
from django.core.management.base import BaseCommand, CommandError
from django_scopes import scopes_disabled
from django.utils.translation import gettext_lazy as _
from cookbook.models import Recipe
# can be executed at the command line with 'python manage.py rebuildindex'
class Command(BaseCommand):
help = _('Rebuilds full text search index on Recipe')
def handle(self, *args, **options):
if settings.DATABASES['default']['ENGINE'] not in ['django.db.backends.postgresql_psycopg2', 'django.db.backends.postgresql']:
self.stdout.write(self.style.WARNING(_('Only Postgress databases use full text search, no index to rebuild')))
try:
with scopes_disabled():
search_vector = (
SearchVector('name', weight='A')
+ SearchVector('description', weight='B'))
Recipe.objects.all().update(search_vector=search_vector)
self.stdout.write(self.style.SUCCESS(_('Recipe index rebuild complete.')))
except:
self.stdout.write(self.style.ERROR(_('Recipe index rebuild failed.')))