Django Tutorial: `filter()`, `exclude()`, and `get()`

beginner
7 min

Django Tutorial: filter(), exclude(), and get()

Welcome to our comprehensive Django tutorial where we'll dive into the powerful filtering and retrieval methods - filter(), exclude(), and get(). By the end of this tutorial, you'll be equipped to manage your data effectively in your Django applications.

Introduction 🎯

In this lesson, we'll explore how to filter, exclude, and retrieve specific objects from the database using Django's queryset methods. These methods are essential for manipulating data in your Django applications.

Prerequisites πŸ“

  • Familiarity with Python
  • Basics of Django

Filtering Objects πŸ’‘

The filter() method is used to filter objects based on a certain condition. Here's a simple example:

python
from django.shortcuts import get_object_or_404 def list_items(request): items = Item.objects.filter(price__gt=100) return render(request, 'items.html', {'items': items})

In the above example, we're filtering Item objects where the price is greater than 100. Here, price__gt=100 is the condition.

πŸ’‘ Pro Tip: Use double underscores (__) to access the attribute name in the database, even if it doesn't follow Python's naming conventions.

Excluding Objects πŸ“

The exclude() method does the opposite of filter(). It excludes objects that match a certain condition. Here's an example:

python
def list_items(request): items = Item.objects.exclude(price__lt=50) return render(request, 'items.html', {'items': items})

In this example, we're excluding Item objects where the price is less than 50.

Retrieving a Single Object: get() πŸ’‘

The get() method is used to retrieve a single object from the database based on a certain condition. Here's an example:

python
def view_item(request, item_id): item = get_object_or_404(Item, id=item_id) return render(request, 'item.html', {'item': item})

In this example, we're retrieving a specific Item object based on its id. If no object is found, Django will return a 404 Not Found error.

πŸ’‘ Pro Tip: Use get_object_or_404() function to avoid handling exceptions when retrieving objects.

Practice Time 🎯

Quick Quiz
Question 1 of 1

Given the following code, what does the `filter()` method do?


In the next part of this tutorial, we'll delve deeper into Django's queryset methods and learn how to use advanced filters and ordering. Stay tuned! 🎯