I'm seeing an error when running my tests, i.e. $ ./manage.py test --settings=my.test.settings
django.db.utils.ProgrammingError: relation "<relation name>" does not exist
This is after running ./manage.py makemigrations && migrate
.
This error turns out (usually) to be caused, ultimately, by failing to create the initial migration for a new app. the error was resolved by running $ ./manage.py makemigrations <my new app module name> && migrate
NOTE: makemigrations
DOES NOT AUTOMATICALLY CREATE THE INITIAL MIGRATION FOR NEW APPS
makemigrations
should create the initial migration for new apps, especifically if the new app is listed in INSTALLED_APPS
This error happened to me because I was trying to run a piece of code that accessed the database when Django starts.
# file name: blog/apps.py
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
def ready(self):
from .business import markdown_to_html
markdown_to_html.refresh_posts() # This method access the database.
Then, when I executed the tests: python manage.py test
, this code fragment was executed and I got the error you mentioned.
Why? It is explained here: https://docs.djangoproject.com/en/3.0/ref/applications/#django.apps.AppConfig.ready
As I needed to execute this method only once, I decided to create a management command.
Here is the code:
# file name: md_to_html.py
from django.core.management.base import BaseCommand
from blog.business import markdown_to_html
class Command(BaseCommand):
help = 'Convert posts written in markdown to html'
def handle(self, *args, **options):
markdown_to_html.refresh_posts()
self.stdout.write(self.style.SUCCESS('HTML files created'))
Before starting the Django project, I executed the command using the following line: python manage.py md_to_html
. In this way I ensured this code is executed only once in a safely.
Now when I run the tests I don't get the error anymore.
Here you can find more information about how to create a custom management command in Django: https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/
This link describes how to test a custom management command: https://docs.djangoproject.com/en/3.0/topics/testing/tools/#topics-testing-management-commands
In case you faced this issue while using pytest-django package, check that your haven't created new migrations with --reuse-db
option in your pytest.ini
I had a similar case, table wasn't created just for one model and i figured out that the model is placed in models directory and is not added to models/__init__.py
. Just added it to __init__.py
and magic happened.
models tree looks like:
models/
__init__.py
model.py
model.py
class ModelName(models.Model):
pass
__init__.py
from .model import ModelName
__all__ = [
'ModelName',
]