我想在一个特定的Postgresql模式中创建一个新表(即“schema1)从Django迁移。
尽管从this blog或this post开始遵循方法1,但迁移将表发送到默认模式“public”而不是“schema1”。
在settings.py
中,我有:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'OPTIONS': {
'options': '-c search_path=django,public'
},
'NAME': 'myDB',
'USER': 'username',
'PASSWORD': '***',
'HOST': 'my.host.address',
'PORT': '1234',
},
'schema1': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'OPTIONS': {
'options': '-c search_path=schema1,public'
},
'NAME': 'myDB',
'USER': 'username',
'PASSWORD': '***',
'HOST': 'my.host.address',
'PORT': '1234',
}
}
#Path to DBrouter to handle PG schemas https://stackoverflow.com/a/51007441/3976696
DATABASE_ROUTERS = ('djangogirls.dbrouters.MyDBRouter',)
字符串
在djangogirls/dbrouters.py
中,我有:
from legacydbapp.models import MyUser
# Include here any class (i.e. table) that belongs to the schema "schema1"
ROUTED_MODELS_SCHEMA1 = [MyUser]
class MyDBRouter(object):
"""
A router to place DB queries into correct schema depending on considered tables.
"""
def db_for_read(self, model, **hints):
if model in ROUTED_MODELS_SCHEMA1 :
return 'schema1'
return None
def db_for_write(self, model, **hints):
if model in ROUTED_MODELS_SCHEMA1 :
return 'schema1'
return None
型
我尝试迁移的模型类,在models.py
中:
class MyUser(models.Model):
first_name = models.CharField(max_length=30, default='',null=True, blank=True)
last_name = models.CharField(max_length=30, default='', null=True, blank=True)
profession = models.CharField(max_length=32,default='', null=True, blank=True)
def __str__(self):
return self.first_name + " " + self.last_name
class Meta:
managed = True
db_table = 'myuser'
型
我运行了以下命令:
$ python manage.py makemigrations legacydbapp
$ python manage.py sqlmigrate legacydbapp 0001_initial
$ python manage.py migrate legacydbapp
型
sqlmigrate返回以下SQL:
BEGIN;
--
-- Create model MyUser
--
CREATE TABLE "myuser" (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NULL,
"last_name" varchar(30) NULL,
"profession" varchar(32) NULL);
COMMIT;
型
如果DB路由器正常工作,我希望SQL读取的是CREATE TABLE "schema1.myuser"
,但实际情况并非如此。是我在某个地方搞砸了,还是这在Django 2.1.5中根本无法实现?
2条答案
按热度按时间kxeu7u2r1#
运行migrate时,必须显式提供数据库定义的名称:
字符串
要确保模型
MyUser
仅在特定数据库中创建,路由器必须实现.allow_migrate()
uqxowvwt2#
hi要将一个模型迁移到特定的scema,您可以用途:
字符串