django 2种方式读取外部的DB

For retrieving the data, you have two options:

1) You can create Django models that correspond to your tables in the MySQL database.

You can do this manually, or you can use the "inspectdb" command with manage.py to give yourself a good starting point. Then do something like this:

def myview(request):
  rows = MyModel.objects.using('mysql').all()
  return render_to_response("mytemplate.html", {"rows" : rows })

参考:https://docs.djangoproject.com/en/dev/topics/db/multi-db/

2) You can manage the connections and queries manually within your app. This is perfectly valid within a view:

def myview(request):
  conn = MySQLdb.connect("connection info here")
  try:
    cursor = conn.cursor()
    cursor.execute("select * from mytable")
    rows = cursor.fetchall()
  finally:
    conn.close()

  return render_to_response("mytemplate.html", {"rows" : rows})
posted @ 2020-09-03 12:49  花生与酒  阅读(282)  评论(0编辑  收藏  举报