Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter vs get in models

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.

like image 642
user1050619 Avatar asked Mar 06 '13 15:03

user1050619


People also ask

What is difference between filter and get in Django?

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.

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.

Is Django filter lazy?

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.

What is get in Django?

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.


2 Answers

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)
like image 111
alfonsoolavarria Avatar answered Oct 13 '22 15:10

alfonsoolavarria


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.

like image 24
Priyank Avatar answered Oct 13 '22 15:10

Priyank