3 Ways to Disable Django Migrations for Unit Tests

Learn how to speed up your tests by disabling migrations for unit testing.

Picture of Nsikak Imoh, author of Macsika Blog
White background with the text 3 Ways to Disable Django Migrations for Unit Tests
White background with the text 3 Ways to Disable Django Migrations for Unit Tests

This post is part of the tutorial series titled Learn to Use Django with FastAPI Frameworks

Table of Content

In Django framework, the model migrations are certainly a great feature.

However, it can quickly become annoying when running tests because it slows down the process.

This is worst if you have a large migration history.

Here is a tutorial on how you can speed up your tests by disabling migrations for unit testing.

How to Ignore Django Migrations for Unit Tests

Create a file named test_settings.py. Or, If your setting configurations are divided into multiple environments, create a file called tests.py or ci.py in the settings module.

  1. Disable Migrations with MIGRATION_MODULES settings configuration

    For Django versions >= 1.9, a viable option is using the MIGRATION_MODULES setting, which is intended to define a custom name for an app's migration module in a dictionary format.

    However, you can use it in a test settings file to skip migrations when unit testing your project.

    The tables will still be created for the apps' models that are listed.

    This method is mostly useful if you want to control the list of apps to skip migrations file.

    We normally keep these settings in its own settings file, so we can run test with or without migrations based on the input in the command-line.

    However, if you use the MIGRATION_MODULES in your main project settings, use the command

    migrate  --run-syncdb
    
    Highlighted code sample.

    option if you want to create tables for the app when running the test.

    Here's how to disable migrations with MIGRATION_MODULES settings configuration:

    	from settings import *
    
    	MIGRATION_MODULES = {
    	    'auth': None,
    	    'contenttypes': None,
    	    'default': None,
    
    Highlighted code sample.
Get the Complete Code of Django and FastAPI Combo Tutorials on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?