Django "ProgrammingError: relation does not exist" (unmigrated DB) in CI
Postgres reports "relation does not exist" when Django queries a table that was never created. In CI this means migrations did not run (or ran against a different database) before the query or test executed.
What this error means
A query or test fails with "django.db.utils.ProgrammingError: relation \"app_order\" does not exist" against a freshly created CI database.
django.db.utils.ProgrammingError: relation "app_order" does not exist
LINE 1: SELECT ... FROM "app_order" ...Common causes
Migrations did not run before the query
The job created an empty database but skipped manage.py migrate, so the tables the query needs do not exist.
Querying a non-test database
A management command ran against the app database directly without migrations, instead of the migrated test database the runner builds.
How to fix it
Run migrations before querying
- Add a
manage.py migratestep before any command that queries the database. - Let
manage.py testor pytest-django build and migrate the test database. - Confirm the same
DATABASESsettings are used by migrate and the test step.
python manage.py migrate --noinput
python manage.py test --noinputLet the test runner own migrations
pytest-django creates and migrates the test database for you when the db fixture is requested.
import pytest
@pytest.mark.django_db
def test_orders():
assert Order.objects.count() == 0How to prevent it
- Run migrate before any step that queries the database.
- Use one DATABASES config for migrate and tests.
- Let pytest-django or manage.py test manage the test schema.