最新亚洲精品福利在线,欧美一区二区三区大片,久久91无码一区二区三区,色哟哟免费观看视频入口,美女裸露双奶头屁股无裸体

Django數(shù)據(jù)庫(kù)操作(執(zhí)行原生SQL的幾種方法)

時(shí)間:2022-01-30 23:11:10 類(lèi)型:python
字號(hào):    

  1.使用extra方法

  解釋?zhuān)航Y(jié)果集修改器,一種提供額外查詢(xún)參數(shù)的機(jī)制

  說(shuō)明:依賴(lài)model模型

  用在where后:

  News.objects.filter(id=1).extra(where=["title='生命的意義'"])

  用在select后

  News.objects.filter(id=1).extra(select={"count":"select count(*) from book"})

  2.使用raw方法

  解釋?zhuān)簣?zhí)行原始sql并返回模型

  說(shuō)明:依賴(lài)model多用于查詢(xún)

  用法:

  student= Book.objects.raw("select * from student")

  for item in student:

  print(item.name)

  3.執(zhí)行自定義SQL

  解釋?zhuān)豪糜螛?biāo)執(zhí)行

  導(dǎo)入:from django.db import connection

  說(shuō)明:不依賴(lài)model

  用法:

  from django.db import connection

  cursor = connection.cursor()

  #插入

  cursor.execute("insert into student(name) values('小強(qiáng)')")

  #更新

  cursor.execute("updatestudent set name='小剛' where id=1")

  #刪除

  cursor.execute("delete from student where name='小王'")

  #查詢(xún)

  cursor.execute("select * from student")

  #返回一行

  raw = cursor.fetchone()

  print(raw)

  # #返回所有

  # cursor.fetchall()


<