1. 程式人生 > 實用技巧 >在django中使用原生sql語句

在django中使用原生sql語句

raw

# 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

## 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)

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中%多用於格式化輸出。