Difference between Django's filter() and get() methods
What is the difference between
mymodel=model.objects.get(name='pol')
and
mymodel=model.objects.filter(name='pol')
The Django QuerySet docs are very clear on this:
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.
Basically use get()
when you want to get a single unique object, and filter()
when you want to get all objects that match your lookup parameters.
Also, on a side note, assuming pol is not available:
if mymodel=model.objects.get(name='pol').exists()==False:
print "Pol does not exist"
you will get: AttributeError: 'Model' object has no attribute 'exists'
but:
if mymodel=model.objects.filter(name='pol').exists()==False:
print "Pol does not exist"
you will get: Pol does not exist.
I.e. If you want to run some code depending on whether a single object can be found, use filter. For some reason exists() works on QuerySet but not the specific object returned with get.
Note that behind the scenes the django get() method runs the filter() method, but checks that the filter results set is exactly one record