ORM操作原生sq
orm执行原生语句
raw()语法查询必须包含主键。
ret = models.Book.objects.raw('select * from app01_book where id=2;')
print(ret) 得到的是RawQuerySet对象 for循环取值
for i in ret:
print(i.title) #海狗的怂逼人生
直接执行自定义SQL
from django.db import connection
cursor = connection.cursor()#cursor就是游标
cursor.execute('select * from app01_book;')
print(cursor.fetchall())
pymysq用法-----
import pymysql
conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='666',database='orm02',charset='utf8')
cursor = conn.cursor()
cursor.execute('select * from app01_book;')
cursor.fetchall()
查看执行的原生语句
配置文件
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}
非学,无以致疑;非问,无以广识