user1050619
user1050619

Reputation: 20856

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.

Upvotes: 13

Views: 6398

Answers (4)

Ryan Gedwill
Ryan Gedwill

Reputation: 118

To add to what others have said... (get returns exactly 1 record, while filter returns a set), an important thing to note is the type of the results.

get() returns an object, while filter returns a queryset type. This means you can do something like

age = User.objects.get(name="Ryan").age

Whereas if you were using filter, you'd need to do a couple extra steps:

ages = User.Objects.filter(name="ryan").values('age')
for user_age in ages:
    print(user_age)

The important thing to note is that filter returns an iterable type with a values() method dictating which fields you want. Get simply returns an object with the fields as attributes, so it is much simpler to get the data you need.

Upvotes: 2

Priyank
Priyank

Reputation: 3868

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.

Upvotes: 2

alfonsoolavarria
alfonsoolavarria

Reputation: 1225

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

 __data = User.objects.get(is_active=1).exclude(id=id)

Error:get() returned more than one User -- it returned 19!, Type:<class 'django.contrib.auth.models.MultipleObjectsReturned'>

------successful-------

__data = User.objects.filter(is_active=1).exclude(id=id)

-------successful------

Check the Link

Upvotes: 2

alfonsoolavarria
alfonsoolavarria

Reputation: 1225

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)

Upvotes: 13

Related Questions