django:如何获取未同步的应用列表?

时间:2015-06-11 11:52:40

标签: python django django-syncdb

当你执行bin/django syncdb一个包含所有已经存在的应用程序的列表时,将返回尚未同步的应用程序。

Synced:
 > south
 > raven.contrib.django
 > django.contrib.staticfiles
     ...

Not synced (use migrations):
 - django_extensions
     ...

如何拦截此信息?我正在查看post_syncdb信号,但call_back不包含我希望的信息。

编辑 也许我不够清楚。我知道我可以这样做:

output = Popen(["bin/django","syncdb"], stdout=subprocess.PIPE).communicate()[0]

或:

def get_syncdb_output():
    content = StringIO()
    call_command('syncdb', stdout=content)
    import ipdb; ipdb.set_trace()
    content.seek(0)
    ansi_escape = re.compile(r'\x1b[^m]*m')
    return ansi_escape.sub('', content.read().decode('utf8'))

但我想知道正在制作这个信息的django类或方法!

1 个答案:

答案 0 :(得分:0)

你知道Django是OSS,不是吗?答案是在django/core/management/commands/syncdb.py的源代码中以纯文本写的。对于Django 1.6.5,它的:

    db = options.get('database')
    connection = connections[db]
    cursor = connection.cursor()

    # Get a list of already installed *models* so that references work right.
    tables = connection.introspection.table_names()
    seen_models = connection.introspection.installed_models(tables)

对于django 1.7.x及以后,您必须查看django/core/management/commands/migrate.py。这是一个更复杂的代码,但基本上你会想要像

这样的东西
    from django.db.migrations.executor import MigrationExecutor
    # Get the database we're operating from
    db = options.get('database')
    connection = connections[db]
    executor = MigrationExecutor(connection)
    print  executor.loader.unmigrated_apps