這部分遷移到了個人部落格中:django中執行原生sql語句
這裡需要補充一下,還有乙個extra方法:
ret = models.student.objects.all().extra(where=['id > %s
'], params=['
1'], order_by=['
-id'])#
print(ret)
#for i in ret:
#print(i)
extra
entry.objects.extra(select=, select_params=(1
,))entry.objects.extra(
where=[
'headline=%s'
], params=
['lennon'])
entry.objects.extra(
where=[
"foo='a' or bar = 'a'", "baz = 'a'"])
entry.objects.extra(
select
=, select_params=(1,), order_by=
['-nid'
])
raw
# 執行原生sqlmodels.userinfo.objects.raw('
select * from userinfo
')# 如果sql是其他表時,必須將名字設定為當前userinfo物件的主鍵列名models.userinfo.objects.
raw('
select id as nid from 其他表')
# 為原生sql設定引數
models.userinfo.objects.
raw('
select id as nid from userinfo where nid>%s
', params=
[12,])
name_map
= person.objects.
raw('
select * from some_other_table
', translations=name_map)
直接執行原生sql
fromdjango.db import connection, connections
cursor
= connection.cursor() # cursor
= connections[
'default'
].cursor
()cursor.execute("""select
*from auth_user where id =
%s""", [1]
)row
=cursor.fetchone() # fetchall()/
fetchmany(..)
queryset = models.course.objects.using('default
').all()
Django執行原生SQL
hey,各位小夥伴,這次怎麼來玩一下,如何使用django執行原生sql 我們都知道,python在web界的扛把子,django,可謂是集大成為統一,各種各樣的外掛程式,forms元件,model模型,admin後台 反正就是乙個字,nb 本次就來學一下,如何在django執行原生語句 在使用dj...
django執行原生sql
一 orm row 方法 只能實現查詢 d list models.article.objects.raw select nid,count nid as num,strftime y m create time as ctime from blog article where user id st...
Django執行原生SQL語句
msg show successfully error tag 0 用connection庫 和原生的sql語句讀資料庫,如下 from django.db import connection 匯入connection sql str select from book str型別的原生sql語句 c...