Reputation: 636
I need to pull data from an external MySQL database to my application. I have added the below lines to my databases dictionary in settings.py file.
'cust': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cust_data',
'HOST': '',
'USER': '',
'PASSWORD': ''
}
Is the engine name right? I have added all other details.
Now is this it? How can I get the data from this database now? Can I simply use an SQL query in my applications views.py?
Now when I enter shell using below command
python manage.py shell
When I execute a query to the MySQL database, it doesn't work. I am sure I am missing something here.
I am stuck here, what am I doing wrong here? How can I run a command to access data from a particular table in the above DB?
Upvotes: 2
Views: 3690
Reputation: 86
It seems that your external MySQL database does not map to your Django models. In that case you have to use django.db.connection object to connect the database and execute the raw SQL query directly. You can use the query result in views.py but it is best to consider whether views.py is the right place to perform the query action.
To test the query in python shell you can try in this way:
>>> from django.db import connections
>>> cursor = connections['cust'].cursor() # Replace 'cust' to other defined databases if necessary.
>>> cursor.execute("YOUR SQL QUERY HERE")
>>> cursor.fetchall()
For the method fetchall()
it should return your result in tuple form.
You can refer more information in the official site from here.
Upvotes: 5
Reputation: 1848
The constant variable is wrong. You have to declare the DATABASES
variable.
In your settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'myhost'
}
}
Just replace the placeholders with the correct values.
Upvotes: 1