Detect whether code is being run in the context of migrate/makemigrations command

Here is a fairly non hacky way to do this (since django already creates flags for us) :

import sys
def lazy_discover_foreign_id_choices():
    if ('makemigrations' in sys.argv or 'migrate' in sys.argv):
        return []
    # Leave the rest as is.

This should work for all cases.


A solution I can think of would be to subclass the Django makemigrations command to set a flag before actually performing the actual operation.

Example:

Put that code in <someapp>/management/commands/makemigrations.py, it will override Django's default makemigrations command.

from django.core.management.commands import makemigrations
from django.db import migrations


class Command(makemigrations.Command):
    def handle(self, *args, **kwargs):
        # Set the flag.
        migrations.MIGRATION_OPERATION_IN_PROGRESS = True

        # Execute the normal behaviour.
        super(Command, self).handle(*args, **kwargs)

Do the same for the migrate command.

And modify your dynamic choices function:

from django.db import migrations


def lazy_discover_foreign_id_choices():
    if getattr(migrations, 'MIGRATION_OPERATION_IN_PROGRESS', False):
        return []
    # Leave the rest as is.

It is very hacky but fairly easy to setup.