Difference between get() and filter() django

Published on and updated on
by

The main difference between the get and filter in django is that get() returns an object, while filter() returns a queryset.

The main difference between the get and filter in django is that get() returns an object, while filter() returns a queryset. If more than one object is found by the get() method, it will raise an exception.

Let's take a deeper look into this.

Let's create a imaginary blog model and see the practical use of get() and filter() method.

class Blog(models.Model):
	title = models.CharField(max_length=100)
	slug = models.SlugField(max_length=100)
	publish = models.BooleanField(default=False)

Let's create some entries.

b1 = Blog.objects.create(title="Hello World", slug="hello-world", publish=True)
b2 = Blog.objects.create(title="Hello mother", slug="hello-mother", publish=True)

Now, let's understand both methods. First, let's see with get() method.

Django get() method

Now, that we have a blog and two blog posts inside it. So, if I want to create blog single page or blog detail page then I would be using the get() method. We do that in views.py. Let's see it practically.

from .models import Blog

def blog_detail(request, slug):
	post = Blog.object.get(slug=slug)
	context = {"post": post}
	template = "blog/article_detail.html"
	return render(request, context, template)

Now, if we go to the page example.com/hello-world/ we would be able to fetch that specific blog entry's content in our page.

Example 2:

# opening shell by running the command to test the get() method
python manage.py shell

> from .models import Blog
> p1 = Blog.objects.get(id=1)
> print(p1.title)
>> "Hello World"

Django filter() method

Django's filter() method is similar to get() method. The only difference is that it will look for a list of entries instead of a single post. Let's see a practical example:

In views.py

from .models import Blog

def blog_list(request):
	posts = Blog.object.filter(publish=True)
	context = {"posts": posts}
	template = "blog/article_list.html"
	return render(request, context, template)

Now, if we go to the page example.com/posts/ we would be able to fetch the list of blog entries that are marked publish True.

Example 2:

# opening shell by running the command to test the get() method
python manage.py shell

> from .models import Blog
> p = Blog.objects.filter(publish=True)
> for i in p:
..	print(i.title)
> "Hello World"
> "Hello mother"