我在Postgre中为Django项目手动创建了一些表。我也手工创建了模型。当我尝试syncdb
时,它抛出一个数据库错误,并说表已经存在。
如果syncdb先前创建了表,则不会发生这种情况。syncdb如何知道是它创建了表,还是我创建了表?
似乎django维护了一个应用程序和它们的模型的内部缓存。从这里,它知道它是否已经为模型创建了一个表。我想这就是支持自省的原因,这样模型就可以从现有的模式中创建,缓存就可以被正确填充。
从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()]