from django.apps import AppConfig from django.db import connections from django.db.models.signals import post_save import warnings from django.utils.html import strip_tags from django.core.management import call_command class CoreConfig(AppConfig): name = "yamdl_playground.core" loaded = False def ready(self): from .models import Page if not self.loaded: connection = connections["default"] with warnings.catch_warnings(): # Django doesn't like running DB queries during app initialization warnings.filterwarnings("ignore", module="django.db", category=RuntimeWarning) # Run migrations, if there are any call_command("migrate", verbosity=0, no_input=True) with connection.cursor() as cursor: cursor.execute("CREATE VIRTUAL TABLE search_index USING fts5(body, content='');") post_save.connect(self.post_save, sender=Page) self.loaded = True def post_save(self, sender, instance, created, **kwargs): if not created: return with connections["default"].cursor() as cursor: cursor.execute("INSERT INTO search_index(body, rowid) VALUES (%s, %s)", [strip_tags(instance.content), instance.pk])