如何在Django中运行“syncdb”时指定架构名称?

7 投票
2 回答
4620 浏览
提问于 2025-04-17 09:16

假设我有一个叫“my_schema”的数据库结构,我该怎么用“django syncdb”命令为这个特定的结构创建表呢?或者有没有其他更快的方法可以根据我的django模型来创建表?我觉得,默认情况下,django是为“public”这个结构创建表的。

2 个回答

0

我用以下信息设置了一切,结果很顺利。

'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dab_name',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
'OPTIONS': {
'options': '-c search_path=tours' #这是数据库的模式名称
}
}

在postgresql 9和django 1.10.2上测试过。

谢谢@romke

6

首先,你需要确保安装了 psycopg2 这个库,版本要在 2.4.3 及以上。如果你已经安装了这个库,那么你可以在基于字典的数据库配置中,向选项(OPTIONS)里添加模式(schema),方法如下:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    # ...
    'OPTIONS': {
      'options': '-c search_path=my_schema'
    }
  }
}

这个方法是在 postgresql 8.4 和 django 1.3 上测试过的。

  1. http://initd.org/psycopg/docs/module.html?highlight=connect#psycopg2.connect
  2. http://www.postgresql.org/docs/8.4/static/libpq-connect.html#LIBPQ-CONNECT-OPTIONS

撰写回答