码迷,mamicode.com
首页 > 数据库 > 详细

django使用原生SQL的方法

时间:2019-06-27 01:10:31      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:结果   abc   select   djang   返回结果   end   block   实例   语言   

django使用原生SQL的方法

  1. 使用extra:

    models.Book.objects.filter(publisher__name=‘传说中的申小五‘).extra(where=[‘price>50‘])
    models.Book.objects.filter(publisher__name=‘传说中的申小五‘, price__gt=50)
    ?
    models.Book.objects.extra(select={‘count‘: ‘select count(*) from hello_Book‘})
  2. 使用raw:


    Book.objects.raw(‘select * from hello_Book‘) # 返回模型实例
  3. 执行自定义SQL语言:


    from django.db import connection
    ?
    cursor=connection.cursor()
    ?
    # 插入操作
    cursor.execute("insert into hello_author(name) values(‘传说中的申小五‘)")
    ?
    # 更新操作
    cursor.execute("update hello_author set name=‘abc‘ where name=‘bcd‘")
    ?
    # 删除操作
    cursor.execute("delete from hello_author where name=‘abc‘")
    ?
    # 查询操作
    cursor.execute("select * from hello_author")
    ?
    raw=cursor.fetchone() # 返回结果行游标直读向前,读取一条
    cursor.fetchall() # 读取所有
    ?

 

django使用原生SQL的方法

标签:结果   abc   select   djang   返回结果   end   block   实例   语言   

原文地址:https://www.cnblogs.com/zuichuyouren/p/11094679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!