Im a newbie to Django and would like to understand what is the difference between filter vs get
Get
Entry.objects.get(id__exact=14)
Filter
Entry.objects.filter(id__exact=14)
What difference the above statement makes?
Thanks in advance.
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.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Django querysets are lazy You can can take the person_set and apply additional filters, or pass it to a function, and nothing will be sent to the database. This is good, because querying the database is one of the things that significantly slows down web applications.
GET is a dictionary-like object containing all GET request parameters. This is specific to Django. The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.
the get
only brings an element that is equal to what you're looking for but the filter
brings everything related to that item you want.
filter returns many things found. get returns only one thing to what you're looking for
for example:
GET
Task.objects.get(id=1,status=1)
Filter
Groups.objects.filter(user=1)
If you know it's one object that matches your query, use get
. It will fail if it's more than one, and gives the error like this:
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!
Otherwise use filter
, which gives you a list of objects.
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