0

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

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

4

1 回答 1

1

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

syncdb 源中可以清楚地看出该过程是什么,以便确定需要在 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()]
于 2013-05-06T06:02:15.207 回答