Python Django 之 直接执行自定义SQL语句(一)
一、执行自定义SQL方法
1、Executing custom SQL directly
2、Manager.raw()
二、Executing custom SQL directly
Manager.raw() 远远不够,可直接执行自定义SQL,directly execute UPDATE , INSERT , or DELETE queries.
django.db.connection:代表默认的数据库连接
django.db.transaction :代表默认数据库事务(transaction)
用database connection调用 connection.cursor() 得到一个游标(cursor)对象。
然后调用 cursor.execute(sql, [params]) 执行SQL
cursor.fetchone() 或者 cursor.fetchall(): 返回结果行
如果执行修改操作,则调用 transaction.commit_unless_managed()来保证你的更改提交到数据库。
def my_custom_sql():
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
transaction.commit_unless_managed()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
django.db.connections :针对使用多个数据库
from django.db import connections
cursor = connections['my_db_alias'].cursor()
# Your code here...
transaction.commit_unless_managed(using='my_db_alias')
通常我们不需要手动调用 transaction.commit_unless_managed( ),我们可以这样做:
@commit_on_success
def my_custom_sql_view(request, value):
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value])
transaction.set_dirty()
# so no call to set_dirty() is required.
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [value])
row = cursor.fetchone()
查看Django ORM执行的SQL语句 : connection.queries
三、raw()方法
1、raw()用法
Manager. raw ( raw_query , params=None , translations=None )
用法:
>>> for p in Person.objects.raw('SELECT * FROM Person LIMIT 2'):
... print p
John Smith
Jane Jones
注意,原始SQL里的model,如果在 db_table 没有定义,则使用app的名称,后面下划线 后面接模型类的名称,如"Myblog_New";上面的例子,在定义类的时候已经这样处理了:
Class New(models.Model):
......
......
#自定义表名
class Meta:
db_table = 'New'
2、查询字段隐射到模型字段(Mapping query fields to model fields)
>>> Person.objects.raw('''SELECT first AS first_name,
... last AS last_name,
... bd AS birth_date,
... pk as id,
... FROM some_other_table''')
返回一个RawQuerySet对象
3、索引查找(Index lookups)
first_person = Person.objects.raw('SELECT * from myapp_person LIMIT 1')[0]
#然而,索引和切片不是在数据库级别上执行(除LIMIT外)
4、延迟模型字段(Deferring model fields)
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
... print p.first_name, # 这将检索到原始查询
... print p.last_name # 这将检索需求
...
John Smith
Jane Jones
这个例子其实检索了三个字段,一个主键(必需)、一个原始SQL字段、一个需求字段。这里主键字段不能省略,否则会出错,如下:

5、传递参数(Passing parameters into raw() )
注意两点:
(2)、这种方式不对:
Error:
>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)
Python Django 之 直接执行自定义SQL语句(一)的更多相关文章
- Python Django 之 直接执行自定义SQL语句(二)
转载自:https://my.oschina.net/liuyuantao/blog/712189 一般来说,最好用 Django 自带的模型来实现这些操作.这里仅仅只是为了学习使用原始 SQL 而做 ...
- 在django中,执行原始sql语句
extra()方法 结果集修改器,一种提供额外查询参数的机制 使用extra: 1:Book.objects.filter(publisher__name='广东人员出版社').extra(where ...
- Django之ORM执行原生sql语句
django中的ORM提供的操作功能有限,在模型提供的查询API不能满足实际工作需要时,可以在ORM中直接执行原生sql语句. Django 提供两种方法使用原生SQL进行查询:一种是使用raw()方 ...
- Django 之 查看执行的sql语句
前提: 我的app名称为core,models.py内容如下: # coding:utf-8 from django.db import models # Create your models her ...
- EntityFramework 4/5/6 中执行自定义SQL语句
参考:http://www.cnblogs.com/chengxiaohui/articles/2092001.html 在EF4(.NET 4)中,我们有了全新的API:ObjectContext ...
- python学习-- 在django中,执行原始sql语句
from django.shortcuts import render, redirect from news.models import Article, Column def test(reque ...
- thinkjs中自定义sql语句
一直以为在使用thinkjs时,只能是它自带的sql语句查询,当遇到类似于这样的sql语句时,却不知道这该怎样来写程序,殊不知原来thinkjs可以执行自定义sql语句 SELECT * from a ...
- django系列5.4--ORM中执行原生SQL语句, Python脚本中调用django环境
ORM执行原生sql语句 在模型查询API不够用的情况下,我们还可以使用原始的SQL语句进行查询. Django 提供两种方法使用原始SQL进行查询:一种是使用raw()方法,进行原始SQL查询并返回 ...
- django框架 - 实时查看执行的sql语句
django框架采用的ORM模型,我们可以通过mysql的日志记录实时看到执行的sql语句,具体步骤如下: 第一步:找到mysql的配置文件 第二步:编辑mysql配置文件 第三步:重启mysql 第 ...
随机推荐
- java 数据导入xls
@RequestMapping("admin/doorDesign/getexcel.do") public void getExcel(String name,String ph ...
- 动态规划-最大的正方形面积 Maximal Square
2018-09-13 19:19:44 问题描述: 问题求解: 方法一: 使用动态规划来求解,算法时间复杂度O(n^2). dp[i][j] : 以(i, j)为右下角的面积最大的正方形的边长. 初始 ...
- 实例对比 hibernate, spring data jpa, mybatis 选型参考
原文: 最近重构以前写的服务,最大的一个变动是将mybatis切换为spring data jpa,切换的原因很简单,有两点:第一.它是spring的子项目能够和spring boot很好的融合,没有 ...
- pandas选择单元格,选择行列
首先创建示例df: df = pd.DataFrame(np.arange(16).reshape(4, 4), columns=list('ABCD'), index=list('5678')) d ...
- LeetCode--011--盛最多水的容器(java)
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) .在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0).找出其中的两条线, ...
- WARNING: CPU: 0 PID: 1 at ./arch/x86/include/asm/fpu/internal.h:373
------------[ cut here ]------------WARNING: CPU: 0 PID: 1 at ./arch/x86/include/asm/fpu/internal.h: ...
- confirm提示弹出确定和取消按钮
js----> var con = confirm('这是一个确定加取消的提示窗口') if(con==true){ document.write("点击了确定按钮") }e ...
- PHP工厂模式计算面积与周长
<?phpinterface InterfaceShape{ function getArea(); function getCircumference();} /** * 矩形 */class ...
- layui checkbox无法显示出来问题
{type:'checkbox'} // ,{field: 'product_id', hide: 'true'} ,{field: 'id', title: 'ID', width: 90, fix ...
- hdu5608杜教筛
题意:给定函数\(f(x)\),有\(n^2-3*n+2=\sum_{d|n}f(d)\),求\(\sum_{i=1}^nf(i)\) 题解:很显然的杜教筛,假设\(g(n)=n^2-3*n+2\), ...