如果不想定义model,直接执行自定义SQL,可如下操作:

1. 通过 connections获取db连接,如果是多个数据库,connections['dbName'] 来选择

2. 获取游标 cursor

3. 执行sql: cursor.execute(sql)

4.获取返回结果:fetchone,fetchall (fetchall返回的是元祖,非字典)

from django.db import connections
cursor = connections['test_db'].cursor()
cursor.execute('SELECT * FROM ...')
# fetchall返回的是元祖...
users = cursor.fetchall()

 

参考:

https://blog.csdn.net/iloveyin/article/details/46380619

https://blog.csdn.net/qq_37099834/article/details/82754170

posted on 2019-01-07 18:10  蛋尼  阅读(614)  评论(0编辑  收藏  举报