脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - django中使用原生sql语句的方法步骤

django中使用原生sql语句的方法步骤

2021-09-26 00:26小寒韩 Python

这篇文章主要介绍了django中使用原生sql语句的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

raw

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# row方法:(掺杂着原生sql和orm来执行的操作)
res = cookbook.objects.raw('select id as nid from epos_cookbook where id>%s', params=[1, ])
print(res.columns) # ['nid']
print(type(res)) # <class 'django.db.models.query.rawqueryset'>
 
# 在select里面查询到的数据orm里面的要一一对应
res = cookbook.objects.raw("select * from epos_cookbook")
print(res)
for i in res:
  print(i.create_date)
  print(i)
  
res = cookbook.objects.raw('select * from epos_cookbook where id>%s', params=[1, ])
# 后面可以加参数进来
print(res)
for i in res:
  # print(i.create_date)
  print(i)

extra

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
## select提供简单数据
# select age, (age > 18) as is_adult from myapp_person;
person.objects.all().extra(select={'is_adult': "age > 18"}) # 加在select后面
 
## where提供查询条件
# select * from myapp_person where first||last ilike 'jeffrey%';
person.objects.all().extra(where=["first||last ilike 'jeffrey%'"]) # 加一个where条件
 
## table连接其它表
# select * from myapp_book, myapp_person where last = author_last
book.objects.all().extra(table=['myapp_person'], where=['last = author_last']) # 加from后面
 
## params添参数
# !! 错误的方式 !!
first_name = 'joe' # 如果first_name中有sql特定字符就会出现漏洞
person.objects.all().extra(where=["first = '%s'" % first_name])
# 正确方式
person.objects.all().extra(where=["first = '%s'"], params=[first_name])

connection(类似pymysql)

?
1
2
3
4
5
6
7
8
9
10
11
12
from django.db import connection
 
 cursor=connection.cursor()
 # 如果需要配置数据库
 # cursor=connection['default'].cursor()
 
 cursor.execute('select * from app01_book')
 
 ret=cursor.fetchall()
 
 print(ret)
 #((2, '小时光', decimal('10.00'), 2), (3, '未来可期', decimal('33.00'), 1), (4, '打破思维里的墙', decimal('11.00'), 2), (5, '时光不散', decimal('11.00'), 3))

注意:如果在sql语句中有用到除法(%),需要使用%%来转义,因为在str中%多用于格式化输出。

到此这篇关于django中使用原生sql语句的方法步骤的文章就介绍到这了,更多相关django使用原生sql语句内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_46237597/article/details/112177897

延伸 · 阅读

精彩推荐