Debugging “Django migration is not running”

Gaurav Toshniwal
dubizzle Engineering
2 min readOct 15, 2018

I’ll not cover the common case of some migration that was not applied but somehow the fields were created and you should rollback the migration or fake the previous migration and re-run the migration etc.

A simple migration of mine — which was just creating some fields for an existing model was not executing. This is an unexpected behavior where I had tried all of the above and I started feeling dizzy.

In the course of debugging I figured out that the allow_migrate method of database router was returning False when it should have returned None.

Django has a setting DATABASE_ROUTERS which will be used to determine which database to use when performing a database query.

From the docs:

if you want to implement more interesting database allocation behaviors, you can define and install your own database routers.

A database router class implements up to four methods:

  • db_for_read(model, **hints)
  • db_for_write(model, **hints)
  • allow_relation(obj1, obj2, **hints)
  • allow_migrate(db, app_label, model_name=None, **hints)

From the documentation:

allow_migrate(db, app_label, model_name=None, **hints)

Determine if the migration operation is allowed to run on the database with alias db. Return True if the operation should run, False if it shouldn’t run, or None if the router has no opinion.

In my case, someone had installed a database router that was returning false when it should have returned None:

def allow_migrate(self, db, model):
""" Make sure the x app only appears on the 'x' db """
response = False
if model._meta.app_label == self.APP_LABEL:
response = db == settings.DB_X_NAME
return response

I just changed the part response = False to response = None and bam! It worked like a charm.

--

--

Gaurav Toshniwal
dubizzle Engineering

geek, entrepreneur, ex-Aasaanjobs, developer, IITB graduate