Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Django's filter() and get() methods

Tags:

django

What is the difference between

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

and

mymodel=model.objects.filter(name='pol')
like image 272
Pol Avatar asked Jul 11 '10 05:07

Pol


People also ask

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What does filter return in Django?

Django provides a filter() method which returns a subset of data. It accepts field names as keyword arguments and returns a QuerySet object. As database has only one record where name is 'tom' , the QuerySet object contains only a single record.

Can you filter by property Django?

Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


2 Answers

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.

like image 199
Sam Dolan Avatar answered Oct 23 '22 23:10

Sam Dolan


Note that behind the scenes the django get() method runs the filter() method, but checks that the filter results set is exactly one record

like image 31
Aviah Laor Avatar answered Oct 23 '22 22:10

Aviah Laor