← Back to Chapters

QuerySet Filtering in Django

? QuerySet Filtering in Django

? Quick Overview

Django QuerySets allow you to retrieve and manipulate database records efficiently. Common filtering methods like filter(), get(), and exclude() help narrow down results based on conditions.

? Key Concepts

  • QuerySets are lazy and chainable
  • Filtering does not hit the database immediately
  • Each method returns a new QuerySet

? Syntax / Theory

QuerySet methods apply SQL-like conditions using Pythonic syntax with field lookups.

? filter() Method

? View Code Example
# Filter products using conditions
from .models import Product
products = Product.objects.filter(price__gt=100)
products_in_category = Product.objects.filter(category='Electronics')

? get() Method

? View Code Example
# Retrieve a single unique object
from .models import Product
product = Product.objects.get(id=1)
product_by_name = Product.objects.get(name='Laptop')

? exclude() Method

? View Code Example
# Exclude matching records
from .models import Product
products_not_in_category = Product.objects.exclude(category='Electronics')
products_above_50 = Product.objects.exclude(price__lt=50)

? Combining QuerySet Methods

? View Code Example
# Chain multiple QuerySet methods
from .models import Product
products = Product.objects.filter(category='Electronics', price__gt=100)\
.exclude(stock=0)\
.order_by('price')

? Live Output / Explanation

Each chained method refines the query. Django executes the final SQL query only when data is accessed.

?️ Interactive Simulator

Select a filter below...
ID Product Category Price ($) Stock

? Use Cases

  • Filtering products by price or category
  • Fetching a single record safely
  • Excluding invalid or inactive records

✅ Tips & Best Practices

  • Prefer filter() over get() unless uniqueness is guaranteed
  • Chain filters for readability
  • Handle exceptions when using get()

? Try It Yourself

  • Query products priced above 50 excluding zero stock
  • Experiment with chained filters
  • Sort results using order_by()