Skip to content

Instantly share code, notes, and snippets.

@emakarov
Created December 16, 2016 14:47
Show Gist options
  • Save emakarov/cfbcd55d9c3dda3d163bcfe4c08c31cb to your computer and use it in GitHub Desktop.
Save emakarov/cfbcd55d9c3dda3d163bcfe4c08c31cb to your computer and use it in GitHub Desktop.
How to get name of last migration in django
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections
from django.db.migrations.loader import MigrationLoader
# code from command showmigrations is used and adopted as a function
def get_migrations(connection, app_names=None):
"""
Get a list of all migrations on the system, or only those of
some named apps.
"""
# Load migrations from disk/DB
loader = MigrationLoader(connection, ignore_no_migrations=True)
graph = loader.graph
# If we were passed a list of apps, validate it
if app_names:
invalid_apps = []
for app_name in app_names:
if app_name not in loader.migrated_apps:
invalid_apps.append(app_name)
if invalid_apps:
raise CommandError("No migrations present for: %s" % (", ".join(invalid_apps)))
# Otherwise, show all apps in alphabetic order
else:
app_names = sorted(loader.migrated_apps)
# For each app, print its migrations in order from oldest (roots) to
# newest (leaves).
apps_migrations = {}
for app_name in app_names:
shown = set()
apps_migrations[app_name] = {}
apps_migrations[app_name]['applied'] = [None]
apps_migrations[app_name]['not_applied'] = [None]
for node in graph.leaf_nodes(app_name):
for plan_node in graph.forwards_plan(node):
if plan_node not in shown and plan_node[0] == app_name:
# Give it a nice title if it's a squashed one
title = plan_node[1]
if graph.nodes[plan_node].replaces:
title += " (%s squashed migrations)" % len(graph.nodes[plan_node].replaces)
# Mark it as applied/unapplied
if plan_node in loader.applied_migrations:
apps_migrations[app_name]['applied'].append(title)
else:
apps_migrations[app_name]['not_applied'].append(title)
shown.add(plan_node)
return apps_migrations
# example of usage:
db = DEFAULT_DB_ALIAS
connection = connections[db]
app_label = 'my_app_label' # note that you can actually test several apps at the same time
apps_migrations = get_migrations(connection, app_names=[app_label])
last_migration_name = apps_migrations[app_label]['applied'][-1]
print(apps_migrations)
for application in apps_migrations:
print(application)
print('applied:')
for m in apps_migrations[application]['applied']:
print(m)
print('not applied')
for m in apps_migrations[application]['not_applied']:
print(m)
print('last applied', last_migration_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment