What is the difference between
mymodel=model.objects.get(name='pol')
and
mymodel=model.objects.filter(name='pol')
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
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.
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.
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.
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.
Note that behind the scenes the django get() method runs the filter() method, but checks that the filter results set is exactly one record
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With