Python 使用模型查询辅助外部数据库

Python 使用模型查询辅助外部数据库,python,database,django,model,Python,Database,Django,Model,我想知道如何创建和使用从辅助数据库读取数据的模型。目前,我有下面的代码,用于填充下拉菜单。它位于views.py中 视图.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 FR

我想知道如何创建和使用从辅助数据库读取数据的模型。目前,我有下面的代码,用于填充下拉菜单。它位于views.py中

视图.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})

我读过关于数据库路由器的书,并看了一些例子。然而,我对模型的了解很差,而且大多数示例都与写入数据库有关。如果您能提供任何帮助,我们将不胜感激。

您提出的解决方案没有任何固有的问题。数据库路由主要用于属于您的项目的多个数据库。如果您使用的是外部数据库(特别是那些您几乎没有控制权或没有控制权的数据库),那么您所展示的方法就可以了


但是,可以包装外部数据库,以便使用Django ORM查询它。这些文件很好地涵盖了这一点

你目前的方法有什么问题?对我来说,它看起来不错。从功能上来说,它没有什么问题,但我知道它不是Django的官方做事方式,我想了解一下如何做。如果这个数据库不属于您的项目,它是一种完全可以接受的做事方式。除此之外,您不可能在这里得到比文档中更全面的答案: