gpt4 book ai didi

python - 仅将表迁移到 Django 中 2 个数据库中的 1 个

转载 作者:太空狗 更新时间:2023-10-30 01:27:54 28 4
gpt4 key购买 nike

我试图在 1 个数据库中有选择地创建表,而不是另一个。

在我的示例中,我只想为应用程序创建表:transforms 数据库中的tlocationtcategory。但是,Django 正在 transforms 数据库中创建所有表。

这是数据库路由器配置:

TRANSFORM_APPS = ('tcategory', 'tlocation')


class TransformRouter(object):
"""
A router to control all database operations on models in the
"utils_transform" application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read 'transforms' models go to 'transforms' database.
"""
if model._meta.app_label in TRANSFORM_APPS:
return 'transforms'
return None

def db_for_write(self, model, **hints):
"""
Attempts to write 'transforms' models go to 'transforms' database.
"""
if model._meta.app_label in TRANSFORM_APPS:
return 'transforms'
return None

def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the 'tlocation' app is involved.
"""
if obj1._meta.app_label in TRANSFORM_APPS or \
obj2._meta.app_label in TRANSFORM_APPS:
return True
return None

def allow_migrate(self, db, app_label, model=None, **hints):
"""
Make sure the 'tlocation' app only appears in the 'transforms'
database.
"""
if app_label in TRANSFORM_APPS:
return db == 'transforms'
return None


class DefaultRouter(object):
"""
Catch-all Router for all other DB transactions that aren't in the
``utils_transform`` app.
"""

def db_for_read(self, model, **hints):
return 'default'

def db_for_write(self, model, **hints):
return 'default'

def allow_relation(self, obj1, obj2, **hints):
if obj1._state.db == obj2._state.db:
return True
return None

def allow_migrate(self, db, app_label, model=None, **hints):
return None

我用来运行迁移的命令是:

./manage.py migrate --database=transforms

当我一次只迁移 1 个应用程序时,如下所示,这有效。但是如果 migrate 命令中没有应用过滤器,我就无法运行。示例:

./manage.py migrate tlocation --database=transforms
./manage.py migrate tcategory --database=transforms

最佳答案

您是否为不想创建表的模型尝试过managed = False

class MyModel(models.Model):
...
class Meta:
managed = False

关于python - 仅将表迁移到 Django 中 2 个数据库中的 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36046665/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com