from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from apps.articles.models import Article from .base import SearchBackend class PostgresSearchBackend(SearchBackend): """Computes the search vector on the fly at query time rather than storing/indexing it on Article — keeps the schema identical to the SQLite backend. Revisit with a stored+GIN-indexed column only if an instance's archive grows large enough to need it.""" def search(self, query: str, user, limit: int = 50): if not query.strip(): return Article.objects.none() vector = SearchVector("title", weight="A") + SearchVector("content_html", weight="B") search_query = SearchQuery(query) return ( Article.objects.filter(feed__subscriptions__user=user) .select_related("feed") .annotate(search=vector, rank=SearchRank(vector, search_query)) .filter(search=search_query) .order_by("-rank", "-published_at")[:limit] )