Full answer
Basic search:
vector = SearchVector("title", weight="A") + SearchVector("body", weight="B")
query = SearchQuery("django migration", search_type="websearch")
Article.objects.annotate(search=vector, rank=SearchRank(vector, query)).filter(search=query).order_by("-rank")SearchVectorconverts text to atsvectorwith language-aware stemming (config="english"): "running" matches "run".SearchQuerysupportsplain,phrase,rawandwebsearch(quotes,-exclusion,or), the friendliest for user input.SearchRankscores matches; weights A to D bias title over body. Filter with the match operator (filter(search=query)), notrank__gt=0: PostgreSQL'sts_rankreturns a tiny positive number (1e-20) for rows that do not match.- Computing the vector per query scans the table. For speed store it: a
SearchVectorFieldkept in sync by a trigger, aGeneratedField(Django 5.0+), or updated insave(); then addGinIndex(fields=["search_vector"]), and filter withsearch_vector=query. TrigramSimilarity(extensionpg_trgm) handles typos and partial matches; needsTrigramExtensionin a migration.
JSONField:
Profile.objects.filter(data__grade="A"), nesteddata__address__city="Pune",data__contains={"tags": ["math"]},data__has_key="phone",data__score__gte=50(cast to numeric by the lookup).- A GIN index on the JSON column accelerates
contains,has_keyand related operators; B-tree expression indexes help specific keys:Index(KeyTextTransform("grade", "data"), name=...). - Use JSON for sparse, schemaless attributes; keep fields you filter, join or constrain often as real columns.
Enabling: add django.contrib.postgres to INSTALLED_APPS and create extensions with CreateExtension operations in migrations. Remember that stemming depends on language configuration, and that search ranking is relevance in the linguistic sense, not business ranking.
import os
import sys
import types
import django
from django.conf import settings
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.postgres", "school"],
DATABASES={"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ.get("PGDATABASE", "school"),
"USER": os.environ.get("PGUSER", "postgres"),
"PASSWORD": os.environ.get("PGPASSWORD", ""),
"HOST": os.environ.get("PGHOST", "localhost"),
"PORT": os.environ.get("PGPORT", "5432"),
}},
)
django.setup()
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.db import models, connection
class Article(models.Model):
title = models.CharField(max_length=80)
body = models.TextField()
data = models.JSONField(default=dict)
class Meta:
app_label = "school"
indexes = [GinIndex(fields=["data"], name="article_data_gin")]
with connection.cursor() as cur:
cur.execute("DROP TABLE IF EXISTS school_article")
with connection.schema_editor() as editor:
editor.create_model(Article)
Article.objects.create(title="Running Django migrations", body="How to run and squash migrations safely.", data={"level": "senior", "tags": ["django", "db"], "views": 120})
Article.objects.create(title="Intro to forms", body="Forms validate data. Migrations are not covered here.", data={"level": "fresher", "tags": ["django"], "views": 40})
Article.objects.create(title="FastAPI dependencies", body="Dependency injection with Depends.", data={"level": "mid", "tags": ["fastapi"], "views": 75})
vector = SearchVector("title", weight="A", config="english") + SearchVector("body", weight="B", config="english")
query = SearchQuery("migrating django", search_type="websearch", config="english")
hits = Article.objects.annotate(search=vector, rank=SearchRank(vector, query)).filter(search=query).order_by("-rank")
print("rank>0 would keep every row:", Article.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gt=0).count())
print([(a.title, round(a.rank, 3)) for a in hits])
print([a.title for a in Article.objects.filter(data__level="mid")])
print([a.title for a in Article.objects.filter(data__contains={"tags": ["django"]}).order_by("id")])
print([a.title for a in Article.objects.filter(data__views__gte=70).order_by("id")])
print(Article.objects.filter(data__has_key="level").count())
with connection.cursor() as cur:
cur.execute("DROP TABLE school_article")
Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): rank>0 would keep every row: 3 [('Running Django migrations', 0.995)] ['FastAPI dependencies'] ['Running Django migrations', 'Intro to forms'] ['Running Django migrations', 'FastAPI dependencies'] 3
Key points
- SearchVector, SearchQuery and SearchRank implement PostgreSQL full-text search
- Store the vector and add a GinIndex for speed
- websearch query type suits user input
- JSONField supports key, contains and has_key lookups; GIN accelerates them
- Use trigram similarity for typos; consider a search engine for big needs
Common mistakes
- Computing a SearchVector on every request without storing and indexing it
- Using raw search_type with user input and getting syntax errors
- Forgetting django.contrib.postgres in INSTALLED_APPS
- Storing frequently filtered fields only inside JSON
- Expecting typo tolerance from plain full-text search
Follow-ups
- How do you keep a stored search vector up to date?
- How would trigram search differ?
- When would you move to Elasticsearch or OpenSearch?
Tips
- Explain stemming and rank
- Mention GIN indexes
- Know when JSON is the wrong choice