django 执行原生的sql

例子

from django.db import connection

cr = connection.cursor()
sql = 'select * from auth_permissions where id=%s'
cr.execute(sql,(1,))
cr.fetchone()

查看执行的sql语句:

connection.queries

{'sql': 'select * from auth_permission where id=1', 'time': '0.002'}]

说明:

%s不仅仅可以作为字符串的占位符,向其中传递数字类型也是可以的.而且使用数字不会有引号.
之前总想着会有%d的占位符,看来是想多了.

如果传入的值为None,python 会自动将None 转换为NULL

cr.execute(sql,(None,))
查询结果:
{'sql': 'select * from auth_permission where id=NULL', 'time': '0.000'}]

posted @ 2020-10-05 15:54  那时一个人  阅读(187)  评论(0)    收藏  举报