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测试开发圈”,了解更多测试教程!***
posted @ 2017-03-02 17:19  鲨鱼逛大街  阅读(1090)  评论(0编辑  收藏  举报