django不定义model,直接执行自定义SQL

如果不想定义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

原文地址:https://www.cnblogs.com/dannyyao/p/10234790.html