Returns a dictionary containing lists of all applied migrations
    where the key is the database alias.

def get_applied_migrations(databases=None):
    """
    Returns a dictionary containing lists of all applied migrations
    where the key is the database alias.
    """
    if not databases:
        databases = get_capable_databases()
    else:
        # We only loop through databases that are listed as "capable"
        all_databases = list(get_capable_databases())
        databases = list(
            itertools.ifilter(lambda x: x in all_databases, databases)
        )
    
    results = defaultdict(list)
    for db in databases:
        for x in Migration.objects.using(db).order_by("migration_label"):
            results[db].append(x.migration_label)
    
    return results