Django syncdb - 它是如何知道它是否先前创建了表格,或者我是否这样做了?

时间:2013-03-11 17:20:33

标签: python django django-orm django-postgresql

我在Postgre中为Django项目手动创建了一些表。我也手动创建了模型。当我尝试syncdb时,它会抛出数据库错误,并表示该表已经存在。

如果syncdb先前创建了表,则不会发生这种情况。 syncdb如何知道它是创建表还是创建了表?

1 个答案:

答案 0 :(得分:1)

似乎django维护着应用程序及其模型的内部缓存。它是从这里知道它是否已经为模型创建了一个表。我想这就是支持introspection的原因,因此模型是从现有模式创建的,并且缓存已正确填充。

syncdb source可以看出这个过程是什么,以确定在syncdb上需要做什么:

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

    # Build the manifest of apps and models that are to be synchronized
    all_models = [
        (app.__name__.split('.')[-2],
            [m for m in models.get_models(app, include_auto_created=True)
            if router.allow_syncdb(db, m)])
        for app in models.get_apps()
    ]

    def model_installed(model):
        opts = model._meta
        converter = connection.introspection.table_name_converter
        return not ((converter(opts.db_table) in tables) or
            (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables))

    manifest = SortedDict(
        (app_name, list(filter(model_installed, model_list)))
        for app_name, model_list in all_models
    )

在每个数据库驱动程序中,都有用于获取表名的代码。这是为postgresql:

def get_table_list(self, cursor):
        "Returns a list of table names in the current database."
        cursor.execute("""
            SELECT c.relname
            FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relkind IN ('r', 'v', '')
                AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
                AND pg_catalog.pg_table_is_visible(c.oid)""")
        return [row[0] for row in cursor.fetchall()]