Django进阶Model篇008 - 使用原生sql

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

 

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

二、执行原始sql并返回模型实例

三、直接执行自定义SQL:这种方式完全不依赖model,前面两种还是要依赖model

 

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

>>> Book.objects.filter(publisher__name='人民邮电出版社').extra(where=['price>50'])
>>> Book.objects.filter(publisher__name='人民邮电出版社',price__gt=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()

 


***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***

转载于:https://www.cnblogs.com/guanfuchang/p/6491625.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值