[Django]Django的orm中get和filter的不同,djangoorm
Django的orm中get和filter的不同
Django的orm架構對於業務複雜度不是很高的應用來說還是不錯的,寫起來很方面,用起來也簡單。對於新手來說查詢操作中最長用的兩個方法get和filter有時候一不注意就會犯下一些小錯誤。那麼今天就來小節下這兩個方法使用上的不同。
我常用的是1.5版本的django,就以此為例來說說吧。
文檔
首先對比下兩個函數文檔上的解釋。
get
Returns the object matching the given lookup parameters, which should be in the format described in Field lookups.
get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.
get() raises a DoesNotExist exception if an object wasn’t found for the given parameters. This exception is also an attribute of the model class
filter
Returns a new QuerySet containing objects that do not match the given lookup parameters.
The lookup parameters (**kwargs) should be in the format described in Field lookups below. Multiple parameters are joined via AND in the underlying SQL statement, and the whole thing is enclosed in a NOT().
-
輸入參數
get 的參數只能是model中定義的那些欄位,只支援嚴格匹配
filter 的參數可以是欄位,也可以是擴充的where查詢關鍵字,如in,like等
-
返回值
get 返回值是一個定義的model對象
filter 返回值是一個新的QuerySet對象,然後可以對QuerySet在進行查詢返回新的QuerySet對象,支援鏈式操作
QuerySet一個集合對象,可使用迭代或者遍曆,切片等,但是不等於list類型(使用一定要注意)
-
異常
get 只有一條記錄返回的時候才正常,也就說明get的查詢欄位必須是主鍵或者唯一約束的欄位。當返回多條記錄或者是沒有找到記錄的時候都會拋出異常
filter 有沒有匹配的記錄都可以
本文出自 “orangleliu筆記本” 部落格,請務必保留此出處http://blog.csdn.net/orangleliu/article/details/38597593
django 怎直接用模型代碼(ORM)來當場測試查看查詢資料庫的效果?
在django項目中使用: python manage.py shell
from django.db import connection
#import 相關模型的class
#執行query查詢
print connection.queries
Django常用文法,接受get與post參數的方法
name=request.REQUEST.get('name','xxx')
#get/post請求都可以用這麼來接收參數
#擷取參數name的值;如果請求裡沒有name,則給name賦值xxx