Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

Django OperationalError: no such table (and relation does not exist): how to fix it

django.db.utils.OperationalError: no such table on SQLite, or ProgrammingError: relation does not exist on PostgreSQL, means the table your model needs is not in the database the app is connected to. After a deploy that is usually migrate not run on the production database, migration files never committed, an app missing from INSTALLED_APPS, or a new empty SQLite file. Commit the migrations, run python manage.py migrate against the right database, and check with showmigrations.

By Livops team, the people who build and run LivopsUpdated

The app deployed, and the first request that touches the database fails with one of these, depending on the database:

django.db.utils.OperationalError: no such table: blog_post
django.db.utils.ProgrammingError: relation "blog_post" does not exist

The first is SQLite, the second PostgreSQL. Both mean the same thing: the table is not in the database the app is connected to. This page explains how to read the error, lists the causes after a deploy, most common first, and shows how to check what is applied. For the whole production setup of a Django app, see Django hosting.

What the error means

Django names a model’s table by joining the app label to the model’s class name with an underscore: a model Book in the app bookstore gets the table bookstore_book[11]. So blog_post points at the model Post in the app blog. django_session, auth_user or django_content_type in the message mean Django’s own tables are missing too, and migrate never ran on this database at all.

Django wraps the database driver’s exceptions in its own classes, importable from django.db, which behave exactly like the originals[8]. On PostgreSQL the error carries SQLSTATE 42P01, undefined_table[9], which psycopg maps to UndefinedTable, a ProgrammingError[10]. That is why the same missing table is an OperationalError on SQLite and a ProgrammingError on PostgreSQL.

Migrations are how Django turns your models into tables: makemigrations packages model changes into migration files, and migrate applies those files to a database[1]. The error means that chain is broken somewhere for this database.

Causes, most common first

1. migrate never ran on the production database

Your local database has the tables because you ran migrate on it. The production database is another one. Django’s own workflow is to make migrations once on your development machine and then run the same migrations on staging and production[1]:

python manage.py migrate --noinput

migrate synchronizes the database with the current models and migrations; --noinput suppresses every prompt[2], so it can run unattended in a deploy. Run it on every deploy, before the new version serves requests, with the same settings and environment variables as the app. --database picks the connection to migrate and defaults to default[2]: with several databases, migrate each one the app reads from.

2. The migration files are not in the repository

You ran makemigrations locally, the files sit in blog/migrations/, and they were never committed, or .gitignore drops them. Production then has nothing to apply. Migration files live in a migrations directory inside each app and are designed to be committed to, and distributed as part of, its codebase[1]. Django advises committing the migration and the model change as a single commit, so the production servers get both at once[1].

Check what the repository actually has:

git ls-files '*/migrations/*.py'
git status --short

If the files are missing, commit them and deploy again. Do not run makemigrations in production instead: it writes new files from whatever models it finds[2], which may not match what you tested, and they are lost with the next deploy. To catch a forgotten migration before it ships, makemigrations --check exits with a non-zero status when model changes have no migration[2]; put it in CI.

3. The app is not in INSTALLED_APPS

migrate looks at the INSTALLED_APPS setting and creates tables for the apps listed there[4]. An app that is missing is ignored. Add it by its configuration class, as the tutorial does for polls.apps.PollsConfig[4]:

INSTALLED_APPS = [
    "blog.apps.BlogConfig",
    "django.contrib.admin",
    # ...
]

Then run makemigrations locally, commit the new files and deploy. This often shows up with a production settings file that keeps its own copy of INSTALLED_APPS and was not updated with the new app.

4. A new, empty SQLite file

For SQLite, NAME is the full path to the database file[3]; startproject sets it to BASE_DIR / 'db.sqlite3'[5]. Django opens it with Python’s sqlite3 module[6], which creates the file if it does not exist[7]. So a path that points somewhere new does not fail on connect: it creates an empty database, and the first query reports no such table.

That happens when the path changed between where migrate ran and where the app runs: a relative NAME resolved from another working directory, a path built from a variable that is set differently, or a disk that is mounted somewhere else. Print the path the app actually uses:

python manage.py shell -c "from django.db import connection; print(connection.settings_dict['NAME'])"

Run that, and migrate, with the same settings the app runs with. If the folder does not exist or is not writable, SQLite fails earlier with a different error: see unable to open database file. Django itself does not recommend migrating SQLite in production unless you are very aware of its risks and limitations[1]; for real data, use PostgreSQL.

5. migrate ran at build time, against another database

Some deploy pipelines build the app in a separate step that has no access to the production database. If migrate is put in the build there, one of two things happens: it fails because there is no database to reach, or, when the settings fall back to SQLite whenever DATABASE_URL is not set, it succeeds against a throwaway SQLite file. The build looks fine, and the real database still has no tables.

Run migrate where the app’s database is reachable: as a release or pre-deploy step, or right before the app starts.

6. The code queries the database while Django starts

Django runs AppConfig.ready() during the startup of every management command, and advises against database queries in it[12]. A query there, or in code that runs when a module is imported, fails with no such table before migrate gets a chance to create that table, and so migrate itself fails. Move the query into a view, a task or a function that runs on demand.

How to check what is applied

Run these with the production settings and database:

python manage.py showmigrations
python manage.py migrate --plan
python manage.py migrate --check

showmigrations lists every app Django knows about and its migrations, with [X] next to each applied one; an app without migrations is listed with (no migrations) under it[2]. An app that is not listed at all is not in INSTALLED_APPS. migrate --plan shows the operations migrate would perform, and migrate --check exits with a non-zero status when unapplied migrations are detected[2], which makes it a useful check in a deploy script.

There is also migrate --run-syncdb, which creates tables for apps without migrations. Django says it is not recommended[2]: make the migrations and commit them instead.

On Livops

  • migrate runs before every start. For a Django project laid out the way startproject lays it out, Livops runs python manage.py migrate --noinput before every start, so the tables exist. The build has no database, so migrate never runs there. That covers causes 1 and 5. Causes 2 and 3 it cannot cover: migrate applies only the migration files in your repository, for the apps in INSTALLED_APPS.
  • If the log still says no such table. Livops’s docs give this fix for a log that says no such table or relation ... does not exist: make the migration the pre-deploy command:
.venv/bin/python manage.py migrate --noinput
  • A failed migration keeps the old version. If the pre-deploy command ends with an error, the deploy is predeploy_failed: the new version is not started, the old one keeps serving, and what it said is in the log.
  • PostgreSQL. Add a database in Databases, and its address is written as the DATABASE_URL variable to every service in the environment. You can browse its tables on the database page in the cabinet, which is a quick way to see whether migrate created them. A new staging environment gets an empty copy of each database, with no data copied, so its tables come from migrate too.
  • SQLite on the disk. While the app runs, its code is read-only. /app/data is the project’s own disk, kept across deploys and restarts, and its path is in the DATA_DIR variable. A SQLite file whose name is written literally in the code, such as sqlite3.connect('bot.db'), is linked to the disk for you; if the path comes from a variable, the platform cannot see it. Django’s default NAME is built from BASE_DIR rather than written as a bare file name, so do not count on that: put the file on the disk yourself:
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": Path(os.environ.get("DATA_DIR", BASE_DIR)) / "db.sqlite3",
    }
}

The disk belongs to one app and is not backed up, so once there are customers, orders or payments, Livops’s docs point to a PostgreSQL database instead.

What Livops does for Django: Frameworks. Where an app may write: Files and data. If PostgreSQL refuses the login, see password authentication failed; for missing CSS after the same deploy, Django static files not loading.

Questions

Why does it work on my computer and fail after the deploy?

Your computer's database already has the tables, because you ran migrate on it. The production database is a different one and starts empty. Unless migrate runs against it, with the migration files from your repository, the tables do not exist there.

Should I commit the migrations folder?

Yes. Django's docs say migration files are designed to be committed to, and distributed as part of, the app's codebase. Make them once with makemigrations on your machine, commit them with the model change, and run the same migrations on every server.

Should production run makemigrations?

No. makemigrations writes new migration files from your models, and those belong in your repository. Production only runs migrate, which applies the files you committed. makemigrations --check in CI fails when a model change has no migration yet.

How do I see which migrations are applied?

python manage.py showmigrations lists every app Django knows about and its migrations, with an X next to each one that is applied. An app with no migrations shows (no migrations). Run it with the same settings and database as the app.

Why do I get no such table on SQLite but relation does not exist on PostgreSQL?

It is the same problem worded by two databases. SQLite says no such table and Django raises OperationalError. PostgreSQL reports SQLSTATE 42P01, undefined_table, which psycopg maps to ProgrammingError, and Django passes it on as django.db.utils.ProgrammingError.

Can I use migrate --run-syncdb instead?

It creates tables for apps without migrations, and Django says it is not recommended. Make migrations for the app and commit them instead, so the same schema reaches every database.

Does Livops run migrate for me?

Yes, for a Django project laid out the way startproject lays it out: python manage.py migrate --noinput runs before every start. It never runs in the build, because the build has no database.

Sources

  1. Django docs — Migrations (docs.djangoproject.com). Checked .
  2. Django docs — django-admin and manage.py (docs.djangoproject.com). Checked .
  3. Django docs — Settings (docs.djangoproject.com). Checked .
  4. Django docs — Writing your first Django app, part 2 (docs.djangoproject.com). Checked .
  5. Django source — django/conf/project_template/project_name/settings.py-tpl (6.1) (raw.githubusercontent.com). Checked .
  6. Django source — django/db/backends/sqlite3/base.py (6.1) (raw.githubusercontent.com). Checked .
  7. Python docs — sqlite3 (docs.python.org). Checked .
  8. Django docs — Django Exceptions (docs.djangoproject.com). Checked .
  9. PostgreSQL docs — Appendix A. PostgreSQL Error Codes (postgresql.org). Checked .
  10. Psycopg 3 docs — psycopg.errors (psycopg.org). Checked .
  11. Django docs — Model Meta options (docs.djangoproject.com). Checked .
  12. Django docs — Applications (docs.djangoproject.com). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your Django app

Got a question? — @livops_uz