2010-07-11 43 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