[转]【Django】Django使用原生SQL的方法
-
使用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'})
-
使用raw:
Book.objects.raw('select * from hello_Book') # 返回模型实例
-
执行自定义SQL语言:
from django.db import connectioncursor=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() # 读取所有
---------------------
作者:q1ang
来源:CNBLOGS
原文:https://www.cnblogs.com/q1ang/p/10098786.html
版权声明:本文为作者原创文章,转载请附上博文链接!