django.db.utils.OperationalError: no such table in Django
Run python manage.py makemigrations followed by python manage.py migrate to create all missing database tables.
Root Cause Analysis
This error occurs when a Django application starts or handles a web request that attempts to query database tables, but the underlying tables have not been created in the connected database because migrations have not been applied.
1. Fresh Project Setup Without Initial Migration
Creating a new Django project and running python manage.py runserver or executing standalone queries before running python manage.py migrate causes Django authentication and session middleware to fail with no such table: django_session or no such table: auth_user.
2. New App Created Without makemigrations
Adding a new app to INSTALLED_APPS and defining models without running python manage.py makemigrations app_name leaves the app un-migrated.
3. Switching Database Backends (SQLite to PostgreSQL)
Switching DATABASES settings in settings.py connects to an empty database engine that requires fresh migration execution.
4. Test Database Isolation Failures
Running custom test suites with --keepdb after schema changes without updating migration files.
Reproduction Code (MCVE)
# Simulating Django OperationalError when table is absent
class OperationalError(Exception):
pass
def check_django_table_exists(existing_tables, target_table):
if target_table not in existing_tables:
raise OperationalError(f'django.db.utils.OperationalError: no such table: {target_table}')
check_django_table_exists([], 'django_session')
Solution 1: Run makemigrations and migrate Commands
Execute Django migration commands to synchronize the database schema with all model definitions.
import sys
print('Execute in terminal:')
print('python manage.py makemigrations')
print('python manage.py migrate')
Solution 2: Inspect Migration Status with showmigrations
Use showmigrations to pinpoint un-applied migrations across all installed apps.
print('Check migration application status:')
print('python manage.py showmigrations')
print('# Apply specific app migrations:')
print('python manage.py migrate auth')
print('python manage.py migrate myapp')
A common mistake is manually creating tables in SQL GUI tools (DBeaver/pgAdmin) without creating Django migration files. Django tracks migration history in django_migrations; manual tables cause future migrations to collide. Use python manage.py migrate --fake only when adopting legacy existing schemas. Edge cases occur with custom user models (AUTH_USER_MODEL): custom user models must be created and migrated before any initial migration runs. Contrast this error with django.db.utils.ProgrammingError: relation does not exist, which is the PostgreSQL equivalent message.