I have configured database properly. If I want to access the data from the table hello in the database called genes. What's the proper way to do it? I can't do from books.models import hello as I don't have hello in models.py. The database genes and table hello is not the default Django database. I have two databases. I have already setup Router. I want to now access data. How can I do that? Thanks
-
Not much. Anyway thanks.user1881957– user18819572013-01-02 03:44:21 +00:00Commented Jan 2, 2013 at 3:44
Add a comment
|
1 Answer
You need to do a few things..
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
One you have this set up then you need to create the models.py file for the
models.py
class Hello(models.Model):
"""Hello model"""
field1 = models.CharField(max_length=64)
class Meta:
db_table = u'hello'
managed = False
To do this progmatically..
python manage.py inspectdb
Once this is done - you should be able to Query using standard Django querysets
Hello.objects.all()
5 Comments
user1881957
Thanks for your answer. I had already configured settings.py and added router. Why would I want to create another model? I already have tables and databases. I don't want to recreate models.
rh0dium
You need the model as that is how Django connect to the db. Wait don't forget the meta option
Andrew Gorcester
You can create a model in models.py to represent an existing database and table. That is the typical way to resolve this issue. (You can alternatively just connect to the database outside of the Django ORM entirely by using a database driver directly.)
user1881957
Yeah, it can be done Pythonic way using MYSQLdb module. But I wanted to know if there's a Django way to do that. Is there a tutorial to create a model to represent existing database and tables.
user1881957
Thanks @AndrewGorcester. That's exactly what I want.