2010-07-11 61 views
10

是什麼差()和get()方法

mymodel=model.objects.get(name='pol') 

mymodel=model.objects.filter(name='pol') 
+0

[在Django模型層GET和過濾器之間的差異(的可能的複製http://stackoverflow.com/questions/1541249/difference-between-get-and-filter-in-django - 模型層) – 2017-03-27 14:15:13

回答

26

之間的差異Django QuerySet docs非常清楚這個:

get(**kwargs)¶

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(**kwargs)

Returns a new QuerySet containing objects that match the given lookup parameters.

,當你想獲得一個唯一的對象,而過濾器時,你想要得到匹配您的查詢參數的所有對象基本上用得到。

+0

答案是有用的,我錯過了幾件關於得到(),Sdolan在這裏告訴 – Hafiz 2012-10-27 02:30:13

5

此外,在一個側面說明,假設POL不可用:

if mymodel=model.objects.get(name='pol').exists()==False: 
    print "Pol does not exist" 

您將獲得: AttributeError的: '模型' 對象有沒有屬性 '存在'

但:

if mymodel=model.objects.filter(name='pol').exists()==False: 
    print "Pol does not exist" 

您將得到:Pol不存在。

I.e.如果要根據是否可找到單個對象來運行一些代碼,請使用過濾器。出於某種原因,exists()在QuerySet上工作,但不在get中返回特定對象。

3

需要注意的是幕後的Django的get()方法運行濾波器()方法,但會檢查設置的過濾效果是一個記錄

0

,如果你知道這是一個對象,你的查詢相匹配,使用「得到」。它會失敗,如果它不止一個,並給出這樣的錯誤

Traceback (most recent call last): 
File "<console>", line 1, in <module> 
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 143, in get 
return self.get_query_set().get(*args, **kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 407, in get 
(self.model._meta.object_name, num)) 
MultipleObjectsReturned: get() returned more than one Poll -- it returned 2! 

否則使用「過濾器」,它給你一個對象的列表。

1

get()返回一個匹配查找條件的對象。

filter()返回一個QuerySet的matche查找條件。

例如,以下

Entry.objects.filter(pub_date__year=2006) 

相當於

Entry.objects.all().filter(pub_date__year=2006) 

這意味着過濾器()是稍貴的操作如果模型類具有大的數量的對象,而得到()是直接的方法。

源:Django making queries