我已正确配置数据库。如果我想访问名为hello
的数据库中的表genes
中的数据。这样做的正确方法是什么?我无法从books.models import hello
做到,因为我在models.py中没有打招呼。数据库基因和表hello不是默认的Django数据库。我有两个数据库。我已经设置了Router
。我想现在访问数据。我怎样才能做到这一点?感谢
答案 0 :(得分:1)
你需要做一些事情......
settings.py
DATABASES = {
'genes': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'genes',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3360',
},
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3360',
}
}
DATABASE_ROUTERS = ['genes.routers.GeneRouter',]
routers.py
class GeneRouter(object):
"""A router to control all database operations on models in
the genes application"""
def db_for_read(self, model, **hints):
"Point all operations on genes models to 'genes'"
if model._meta.app_label == 'genes':
return 'remrate'
return None
def db_for_write(self, model, **hints):
"Point all operations on genes models to 'genes'"
if model._meta.app_label == 'genes':
return 'remrate'
return None
def allow_syncdb(self, db, model):
"Make sure the genes app only appears on the 'genes' db"
if model._meta.app_label in ['south']:
return True
if db == 'remrate':
return model._meta.app_label == 'genes'
elif model._meta.app_label == 'genes':
return False
return None
你设置了这个,然后你需要为
创建models.py文件models.py
class Hello(models.Model):
"""Hello model"""
field1 = models.CharField(max_length=64)
class Meta:
db_table = u'hello'
managed = False
要以此方式执行此操作..
python manage.py inspectdb
完成后 - 您应该能够使用标准Django查询集
进行查询Hello.objects.all()