问题描述
我有两个数据库和两个模型:管理员和用户。
I have two databases and two models:the Admin and the user.
我要将模型同步到两个数据库;
管理模型到数据库A和用户模型到数据库B;
I want to sync my models to the two databases;admin model to database A and user model to database B;
如果我将模型路径设置为 INSTALLED_APPS
和 syncdb
,这两个模型将同步到默认数据库。
If I am setting the model path to INSTALLED_APPS
and syncdb
, the two models will sync to the default database.
syncdb
命令(如 sync --database =B
),这两个模型将同步到数据库B.
if I set the database in the syncdb
command such as sync --database="B"
, and the two models will sync to database B.
所以我的问题是,如何将两个模型同步到两个数据库?
So my problem is, how do I sync the two models to two databases?
推荐答案
我完全同意@alecxe使用数据库路由器。我目前使用单个管理界面来管理多个数据库。请注意,所有数据库的身份验证都存储在默认数据库中,因此当您执行 syncdb
(没有任何参数)。
I fully agree with @alecxe on using the database router. I am currently using a single admin interface to manage multiple databases. Note that authentication for all databases are stored in the default database, so when you do the syncdb
(with no arguments).
通用数据库路由器
我找到实现非常灵活和有用。
I found this implementation to be extremely flexible and useful.
Settings.py / p>
Settings.py
# Define the database manager to setup the various projects
DATABASE_ROUTERS = ['manager.router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {'mux_data': 't29_db',
'T50_VATC':'t50_db'}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'fail_over',
'USER': 'SomeUser',
'PASSWORD': 'SomePassword',
'HOST': '127.0.0.1',
'PORT': '',
},
't29_db': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mux_stage',
'USER': 'SomeUser',
'PASSWORD': 'SomePassword',
'HOST': '127.0.0.1',
'PORT': '',
},
't50_db': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 't50_vatc',
'USER': 'SomeUser',
'PASSWORD': 'SomePassword',
'HOST': '127.0.0.1',
'PORT': '',
},
}
示例模型
# Create your models here.
class Card_Test(models.Model):
name = models.TextField(max_length=100)
description = models.TextField(max_length=200)
units = models.TextField(max_length=500)
result_tags = models.TextField(max_length=500)
class Meta:
app_label = 'mux_data'
def __unicode__(self):
return self.name
class Status_Type(models.Model):
status = models.CharField(max_length=25)
class Meta:
app_label = 'mux_data'
def __unicode__(self):
return self.status
这篇关于多个数据库和多个模型在django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!