Django 使用原生sql

原文:http://www.cnblogs.com/guanfuchang/p/6491625.html

注意:使用原生sql的方式主要目的是解决一些很复杂的sql不能用ORM的方式写出的问题。

extra:结果集修改器-一种提供额外查询参数的机制

raw:执行原始sql并返回模型实例


1.使用extra:查询人民邮电出版社出版并且价格大于50元的书籍

Book.objects.filter(publisher__name='人民邮电出版社').extra(where=['price>50'])

2.使用raw

books=Book.objects.raw('select * from hello_book')
for book in books:
   print 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='韩寒' WHERE name='郭敬明'")
cursor.execute("delete from hello_author where name='韩寒'")
cursor.execute("select * from hello_author")
cursor.fetchone()
cursor.fetchall()


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值