Question

I would like to know how to create, and use, a model that reads data from a secondary database. Currently, I have the code below that I use to populate a drop down menu. It is located in views.py.

views.py

def platform_pass_rate(request):
     db = MySQLdb.connect(user='a_user', db='secondary', passwd='something', host='ab-cd')
     cursor = db.cursor()
     cursor.execute('SELECT study FROM study ORDER BY study ASC')
     study_model = [row for row in cursor.fetchall()]
     cursor.execute(
          'SELECT column_name FROM information_schema.columns where table_name = 
          \'finalvalues\' order by ordinal_position')
     study_result = cursor.fetchall()
     db.close()
     study_models = [i for sub in study_model for i in sub]
     study_results = [i for sub in study_result for i in sub]

     return render_to_response("data_form_platform.html", {'our_url': current_url, 
                                                     'study_models': study_models,
                                                  'study_results': study_results})

I have read about database routers, and looked at examples. However, my knowledge of models is poor, and most examples relate to writing to databases. Any help would be greatly appreciated.

Was it helpful?

Solution

There is nothing inherently wrong with the solution that you have presented. The use of database routing is primarily for multiple databases that belong to your project. If you are using external databases (particularly ones over which you have little or no control), then the method you have shown is fine.

However, it is possible to wrap your external database such that it can be queried with the Django ORM. The docs cover this pretty well https://docs.djangoproject.com/en/dev/topics/db/multi-db/.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top