这篇文章给大家分享的是有关django中使用原生sql语句的示例的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
# 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)
## 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])
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语句的示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。