一、执行自定义SQL方法

1、Executing custom SQL directly

     直接执行自定义SQL,这种方式可以完全避免数据模型,而是直接执行原始的SQL语句。

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()
    return row
  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()
    # Data modifying operation
    cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value])
    # Since we modified data, mark the transaction as dirty
    transaction.set_dirty()
    # Data retrieval operation. This doesn't dirty the transaction,
    # so no call to set_dirty() is required.
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [value])
    row = cursor.fetchone()
    return render_to_response('template.html', {'row': row})
查看Django ORM执行的SQL语句 :   connection.queries   

三、raw()方法

1、raw()用法

The raw() manager method can be used to perform raw SQL queries that return model instances:
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)

raw() automatically maps fields in the query to fields on the model.并且是通过名称来匹配,这意味着我们可以使用SQL子句(clause)
>>> 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')[0]
first_person = Person.objects.raw('SELECT * from myapp_person LIMIT 1')[0]
#然而,索引和切片不是在数据库级别上执行(除LIMIT外)

4、延迟模型字段(Deferring model fields)

Fields may also be left out(left out:忽视,不考虑;被遗忘),这意味着该字段的查询将会被排除在根据需要时的加载。
>>> 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() )

如果需要执行参数化查询,您可以使用params参数原始()

注意两点:

(1)、必须使用[参数],否则出错:
(2)、这种方式不对:
Error:
>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)
 
转载自:https://www.cnblogs.com/hello-/articles/9095444.html

Python Django 之 直接执行自定义SQL语句(一)的更多相关文章

  1. Python Django 之 直接执行自定义SQL语句(二)

    转载自:https://my.oschina.net/liuyuantao/blog/712189 一般来说,最好用 Django 自带的模型来实现这些操作.这里仅仅只是为了学习使用原始 SQL 而做 ...

  2. 在django中,执行原始sql语句

    extra()方法 结果集修改器,一种提供额外查询参数的机制 使用extra: 1:Book.objects.filter(publisher__name='广东人员出版社').extra(where ...

  3. Django之ORM执行原生sql语句

    django中的ORM提供的操作功能有限,在模型提供的查询API不能满足实际工作需要时,可以在ORM中直接执行原生sql语句. Django 提供两种方法使用原生SQL进行查询:一种是使用raw()方 ...

  4. Django 之 查看执行的sql语句

    前提: 我的app名称为core,models.py内容如下: # coding:utf-8 from django.db import models # Create your models her ...

  5. EntityFramework 4/5/6 中执行自定义SQL语句

    参考:http://www.cnblogs.com/chengxiaohui/articles/2092001.html 在EF4(.NET  4)中,我们有了全新的API:ObjectContext ...

  6. python学习-- 在django中,执行原始sql语句

    from django.shortcuts import render, redirect from news.models import Article, Column def test(reque ...

  7. thinkjs中自定义sql语句

    一直以为在使用thinkjs时,只能是它自带的sql语句查询,当遇到类似于这样的sql语句时,却不知道这该怎样来写程序,殊不知原来thinkjs可以执行自定义sql语句 SELECT * from a ...

  8. django系列5.4--ORM中执行原生SQL语句, Python脚本中调用django环境

    ORM执行原生sql语句 在模型查询API不够用的情况下,我们还可以使用原始的SQL语句进行查询. Django 提供两种方法使用原始SQL进行查询:一种是使用raw()方法,进行原始SQL查询并返回 ...

  9. django框架 - 实时查看执行的sql语句

    django框架采用的ORM模型,我们可以通过mysql的日志记录实时看到执行的sql语句,具体步骤如下: 第一步:找到mysql的配置文件 第二步:编辑mysql配置文件 第三步:重启mysql 第 ...

随机推荐

  1. Semana i 2018

    Semana i 2018 A Giga-Kilo-Gigabyte 思路: dp水题 代码: #pragma GCC optimize(2) #pragma GCC optimize(3) #pra ...

  2. Codeforces 1073 E - Segment Sum

    E - Segment Sum 思路: 数位dp 我们平时做的数位dp都是求满足条件的数的个数, 这里要求满足条件的数的和 只要在原来的基础上求每一位的贡献就可以了,所以传参数时要传两个 代码: #p ...

  3. XLua与CSharp交互的采坑点 : 热修复返回值为 Int 的CSharp方法

    1.假如CS的一个类中有如下逻辑: using System.Collections; using System.Collections.Generic; using UnityEngine; usi ...

  4. win10 java环境变量

    https://jingyan.baidu.com/article/fd8044fa2c22f15031137a2a.html

  5. 质控工具之TrimGalore使用方法

    TrimGalore 就是一个简单的perl wrapper,打包了fastqc和cutadapt,但是却非常实用. 因为cutadapt的参数选择实在是有够复杂,光接头类型就有5种,还有各种参数,大 ...

  6. 安装EF实体模型框架

    Data Access and Storage > 学习 > Entity Framework > 开始操作 > 空间 - EF 设计器 本视频和分步演练介绍如何使用实体框架设 ...

  7. LeetCode--429--N叉树的层序遍历

    问题描述: 给定一个N叉树,返回其节点值的层序遍历. (即从左到右,逐层遍历). 例如,给定一个 3叉树 : 返回其层序遍历: [ [1], [3,2,4], [5,6] ] 说明: 树的深度不会超过 ...

  8. 02linux 基本命令

    系统环境变量的设置 以nginx为例: 方式一: ~/.bash_profile  这是个人的 /etc/profile 为系统的环境变量 vim /etc/profile.d/nginx.sh #在 ...

  9. jquery快速获得url 的get传值

    <script> var res = location.search.substr(1).split("&"); var arr={}; for (var i ...

  10. 用vivado实现4比特加法器

    `timescale 1ns / 1ps module add_4_beha( a, b, cin, sum ); :] a; :] b; input cin; output sum; :]a; :] ...