Originally published on Djangix.
Your Django app says relation 'blog_post' does not exist, but the model is right there in models.py. This post shows how to find out whether the migration was never applied, never created, faked, or run against the wrong database — and the exact command that fixes each case.
Short answer
Short answer: the error means Django asked PostgreSQL for a table that is not in the database it is connected to. The table name in the message is the one Django expects — usually the app label plus the lowercase model name, such as blog_post. In almost every case the cause is one of four things: the migration was never applied, the migration file was never created or committed, the migration was recorded as applied without ever running, or the app is connected to a different database or schema than the one you migrated. Run python manage.py showmigrations first — it tells you which case you are in within seconds.
What "relation does not exist" actually means
The full error looks like this:
django.db.utils.ProgrammingError: relation "blog_post" does not exist
LINE 1: SELECT ... FROM "blog_post" ...
"Relation" is PostgreSQL's word for a table. The error is PostgreSQL's undefined_table error, SQLSTATE 42P01. It means name resolution failed: the query is legal, but the name in it does not resolve to any table, view or other relation in the schemas PostgreSQL searched.
The name in quotes is the table Django expects. By default Django builds it from the app label and the lowercase model name, joined with an underscore — a Post model in the blog app expects a table called blog_post. You can override it with db_table in the model's Meta class.
It is not a permissions error. A role with no privilege on an existing table gets a different error, 42501 (insufficient_privilege). If you see 42P01, PostgreSQL genuinely cannot find the table where it looked.
SQLite says it differently. The same situation on SQLite raises django.db.utils.OperationalError: no such table: blog_post. The causes and fixes below are the same; only the wording changes.
It is a database problem, not a code problem. Your model, your QuerySet and your view are almost certainly fine. The mismatch is between three things Django keeps in sync: the model classes in your code, the migration files that describe how to build the schema, and the django_migrations table that records which migrations have been applied to a specific database. This error means those three disagree.
Diagnose it in two minutes
Do not start fixing until you know which case you are in. Three checks:
python manage.py showmigrations blog
python manage.py dbshell
Check the migration state. showmigrations marks each migration [X] if it is applied to this database and [ ] if it is not. If the migration that creates your table shows [ ], go to Fix 1.
Check whether the table exists. In dbshell (which opens psql for PostgreSQL), run \dt blog_post or SELECT to_regclass('public.blog_post');. If it returns nothing, the table really is missing. If it returns the table, the problem is the connection or the name, not the migration — go to Fix 4 or Fix 6.
Check which database you are actually on. Print the connection in the same context that fails: python manage.py shell -c "from django.conf import settings; print(settings.DATABASES['default']['NAME'])". Then compare it with the database you ran migrate against. If they differ, go to Fix 4.
Fix 1: the migration was never applied
This is the most common cause. You ran makemigrations, which only writes a migration file — it creates no tables. Or you deployed code without running migrate on the server.
python manage.py migrate blog
python manage.py showmigrations blog
Apply the missing migration, then confirm. The second command should now show [X] next to it.
Make migrate a mandatory deploy step. Run it before the new code starts serving traffic, not after. If new code serves requests while the old schema is still in place, those requests fail with this error until the migration lands.
Preview first on a shared database. python manage.py migrate blog --plan prints the operations Django will run without running them.
Fix 2: the migration file was never created or committed
If showmigrations does not list the migration at all, the file does not exist in the deployed code.
python manage.py makemigrations --check
If it reports changes, the migration was never created. Run python manage.py makemigrations blog, review the file, then run migrate.
If it reports nothing locally but the server still fails, the file was never committed. Check git status — migration files created on a laptop and never pushed are a classic cause. Commit the file, deploy it, then run migrate.
Check the app is installed. makemigrations only inspects apps in INSTALLED_APPS. A model in an app that is not listed there gets no migration at all, and no error tells you why.
Catch this in CI. makemigrations --check exits with status 1 when model changes have no migration, and since Django 4.2 it does not write the missing files. Add it to your pipeline so an uncommitted migration fails the build instead of production.
Fix 3: Django thinks it is applied, but the table is missing
This is the sneaky case: showmigrations shows [X], dbshell shows no table. The migration record in the django_migrations table says the migration ran, but the table was never created — usually because someone ran migrate --fake, the table was dropped by hand, or a restore put the history back without the schema.
First, prove the table is really missing. Use \dt in dbshell as above. Do not fake anything until you have confirmed it.
Back up before you touch migration history. On production, take a database backup first. Rewriting django_migrations rows is safe when done carefully, but a mistake here can make Django refuse to run real migrations later.
Roll the app's record back, faked, then migrate for real:
python manage.py migrate blog zero --fake
python manage.py migrate blog
How this works: the first command marks every migration for the app as unapplied without running any SQL — the tables are already missing, so there is nothing to drop. The second command runs them for real and creates the tables.
If only one migration is affected, fake just that one. Target the migration before it, faked, then migrate normally: python manage.py migrate blog 0002 --fake followed by python manage.py migrate blog.
If the tables already exist and Django is skipping them, use the other fake. When you point Django at a database whose tables already exist (for example, an imported legacy database), migrate --fake-initial skips the initial migration when its tables already exist and runs the rest normally.
Never use --fake to "fix" a migration you have not understood. --fake only changes the record in django_migrations; it runs no SQL. Faking a migration whose table does not exist is exactly how this case is created in the first place.
Fix 4: the app is talking to the wrong database or schema
If the table exists but Django still cannot see it, the app and the migration ran against different targets.
Different database. Databases on one PostgreSQL server are separate namespaces — a connection never sees another database's tables. Compare settings.DATABASES['default']['NAME'] in the failing process with the one migrate used. A common production cause is the deploy script and the app server loading different environment files, so migrate runs against one database while Gunicorn connects to another.
Different schema. PostgreSQL only searches the schemas in search_path, which defaults to "$user", public. A table in a custom schema is invisible to an unqualified reference. Either qualify it or set the path in your database options:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"OPTIONS": {"options": "-c search_path=myschema,public"},
}
}
Different settings module. manage.py migrate and the running app can load different settings files. Run showmigrations with the same settings the app uses and confirm the [X] marks are there.
Different environment. If the app runs in Docker, check the container actually runs migrations on start, and that its volume is not holding an old database file from a previous image.
Fix 5: migrate itself crashes with the error
If python manage.py migrate fails with relation does not exist before it applies anything, some code is querying the database while Django loads — before the tables exist.
The usual suspect is a query at import time. A Model.objects.all() — or any QuerySet that gets evaluated — at module level in models.py, views.py, urls.py or an app's __init__.py runs when Django imports the module, which happens before migrate creates the tables.
Move the query inside a function. Queries belong in views, methods and AppConfig.ready(), not at module level. A QuerySet that is assigned but never evaluated is fine — it is the evaluation (iterating it, calling list(), .count(), .exists() or printing it) that hits the database.
The traceback tells you where. It points at the module that ran the query. Fix that module and migrate will run.
Fix 6: the name in the error is not the name you expect
If the table exists and the connection is right, the name itself is wrong.
A custom db_table. If the model sets db_table in class Meta, Django uses exactly that name. Check it matches the table that exists — including the schema, if one is included.
Case sensitivity. PostgreSQL folds unquoted identifiers to lowercase. A table created with a quoted mixed-case name, such as "Blog_Post", is stored with that exact case, and only a quoted reference with identical case finds it. If the quoted name in the error differs from your table only in case, this is the cause.
A custom user model. If the error names users_user (or your user table) after you added a custom user model, check that AUTH_USER_MODEL = 'users.User' is set in settings and that the app is in INSTALLED_APPS — and that it was set before the first migration ran. Changing AUTH_USER_MODEL after migrations exist is a much bigger job.
Stop it happening again
- Run
makemigrations --checkin CI. It fails the build when a model change has no migration file. - Run
migrate --checkas a deploy gate. It exits with a non-zero status when unapplied migrations exist, without changing anything. - Run migrate before switching traffic. Migrations go on before the new code serves requests, and keep them backwards compatible so old code still works with the new schema.
- Never --fake a migration on a shared database without a reason you can explain. Faking is for schemas that already match, not a shortcut for a failed migration.
- Keep one database per environment, named the same way everywhere. The wrong-database variant of this error is almost always a settings or environment-file mismatch.
Questions and answers
Does "relation does not exist" mean my table was deleted?
No. It means PostgreSQL cannot resolve the name in the schemas it searched. The table may never have been created, may live in another database or schema, or may be spelled differently. Check with \dt in dbshell before assuming anything was deleted.
I ran migrate and it said "No migrations to apply". Why is the table still missing?
That message means Django found no unapplied migrations — either the migration file does not exist in the deployed code (Fix 2), or it is already recorded as applied while the table is missing (Fix 3). Run showmigrations and makemigrations --check to tell the two apart.
Is it safe to use --fake to fix this?
Only when you have proved the schema already matches what the migration would create, or when you are deliberately rolling a record back so you can re-run the migration for real (Fix 3). Faking a migration on a database that does not have the table is how this error is created.
Why does it work locally but fail in production?
Almost always the migration was run locally but not on the production database, the migration file was never committed and deployed, or the app and migrate are using different databases or settings in production. Compare the showmigrations output on the server with your local output.
What is the difference between "relation does not exist" and "no such table"?
They are the same problem on different databases. PostgreSQL reports relation "blog_post" does not exist (SQLSTATE 42P01); SQLite reports no such table: blog_post. The diagnosis and fixes are the same.
Can a ForeignKey cause this error even when my model's table exists?
Yes. If your model has a ForeignKey or ManyToManyField to another model whose table is missing, saving or querying your model can raise the error naming the related model's table. Apply that app's migrations too — the fix is the same, just for a different app.
Read the original article on Djangix: https://djangix.com/blog/relation-does-not-exist-django/
Top comments (0)