[Solved]-Django test runner failing with "relation does not exist" error

8👍

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

👤Ben

1👍

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

0👍

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

Leave a comment