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 第 ...
随机推荐
- Semana i 2018
Semana i 2018 A Giga-Kilo-Gigabyte 思路: dp水题 代码: #pragma GCC optimize(2) #pragma GCC optimize(3) #pra ...
- Codeforces 1073 E - Segment Sum
E - Segment Sum 思路: 数位dp 我们平时做的数位dp都是求满足条件的数的个数, 这里要求满足条件的数的和 只要在原来的基础上求每一位的贡献就可以了,所以传参数时要传两个 代码: #p ...
- XLua与CSharp交互的采坑点 : 热修复返回值为 Int 的CSharp方法
1.假如CS的一个类中有如下逻辑: using System.Collections; using System.Collections.Generic; using UnityEngine; usi ...
- win10 java环境变量
https://jingyan.baidu.com/article/fd8044fa2c22f15031137a2a.html
- 质控工具之TrimGalore使用方法
TrimGalore 就是一个简单的perl wrapper,打包了fastqc和cutadapt,但是却非常实用. 因为cutadapt的参数选择实在是有够复杂,光接头类型就有5种,还有各种参数,大 ...
- 安装EF实体模型框架
Data Access and Storage > 学习 > Entity Framework > 开始操作 > 空间 - EF 设计器 本视频和分步演练介绍如何使用实体框架设 ...
- LeetCode--429--N叉树的层序遍历
问题描述: 给定一个N叉树,返回其节点值的层序遍历. (即从左到右,逐层遍历). 例如,给定一个 3叉树 : 返回其层序遍历: [ [1], [3,2,4], [5,6] ] 说明: 树的深度不会超过 ...
- 02linux 基本命令
系统环境变量的设置 以nginx为例: 方式一: ~/.bash_profile 这是个人的 /etc/profile 为系统的环境变量 vim /etc/profile.d/nginx.sh #在 ...
- jquery快速获得url 的get传值
<script> var res = location.search.substr(1).split("&"); var arr={}; for (var i ...
- 用vivado实现4比特加法器
`timescale 1ns / 1ps module add_4_beha( a, b, cin, sum ); :] a; :] b; input cin; output sum; :]a; :] ...