我有一个名为xyz的应用,在该应用中有2个视图view1.py和view2.py 我将路由器配置为
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality')
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')
quality.automf(3)
service.automf(3)
tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25])
# HERE COMES MY PROBLEM
quality['average'].view()
是否可以从此应用“ xyz”中选择其他数据库。
我的意思是同一应用程序中有两个不同的数据库。
有没有办法或者django首先允许这样做?
答案 0 :(得分:2)
与数据库相关的东西的配置大部分在settings.py文件中完成。因此,要将多个数据库添加到我们的django项目中,我们需要将它们添加到DATABASES字典中。
这些设置进入 Settings.py
DATABASE_ROUTERS = ['path.to.DemoRouter']
DATABASE_APPS_MAPPING = {'user_data': 'users_db',
'customer_data':'customers_db'}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'users_db': {
'NAME': 'user_data',
'ENGINE': 'django.db.backends.postgresql',
'USER': 'postgres_user',
'PASSWORD': 'password'
},
'customers_db': {
'NAME': 'customer_data',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_cust',
'PASSWORD': 'root'
}
}
对于多个数据库,最好谈论数据库路由器。默认路由方案可确保如果未指定数据库,则所有查询都将退回到默认数据库。数据库路由器默认为[]。
将此内容放入models.py
class DemoRouter:
"""
A router to control all database operations on models in the
user application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read user models go to users_db.
"""
if model._meta.app_label == 'user_data':
return 'users_db'
elif model._meta.app_label == 'customer_data':
return 'customer_db'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write user models go to users_db.
"""
if model._meta.app_label == 'user_data':
return 'users_db'
elif model._meta.app_label == 'customer_data':
return 'customer_db'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the user app is involved.
"""
if obj1._meta.app_label == 'user_data' or \
obj2._meta.app_label == 'user_data':
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'users_db'
database.
"""
if app_label == 'user_data':
return db == 'users_db'
return None
将各个模型修改为
class User(models.Model):
username = models.Charfield(ax_length=100)
. . .
class Meta:
app_label = 'user_data'
class Customer(models.Model):
name = models.TextField(max_length=100)
. . .
class Meta:
app_label = 'customer_data'
在使用多个数据库时,很少有有用的命令。
$ ./manage.py migrate --database=users_db
答案 1 :(得分:0)
以上是更多内容的正确答案,请参见完整文档here