1. 程式人生 > >Django的orm中get和filter的不同

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 有沒有匹配的記錄都可以