Check for pending Django migrations

前端 未结 8 2063
孤独总比滥情好
孤独总比滥情好 2021-02-01 13:05

In Django, is there an easy way to check whether all database migrations have been run? I\'ve found manage.py migrate --list, which gives me the information I want,

8条回答
  •  温柔的废话
    2021-02-01 13:37

    Shell

    The only simple solution I've found so far is running

    ./manage.py showmigrations | grep '\[ \]'
    

    which will output an empty string in case all migrations have been applied.

    However, it is closely tied to the output format.

    Python

    I checked the source code of migrate command and it seems like this should do the trick:

    from django.db.migrations.executor import MigrationExecutor
    from django.db import connections, DEFAULT_DB_ALIAS
    
    
    def is_database_synchronized(database):
        connection = connections[database]
        connection.prepare_database()
        executor = MigrationExecutor(connection)
        targets = executor.loader.graph.leaf_nodes()
        return not executor.migration_plan(targets)
    
    # Usage example.
    if is_database_synchronized(DEFAULT_DB_ALIAS):
        # All migrations have been applied.
        pass
    else:
        # Unapplied migrations found.
        pass
    

提交回复
热议问题