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.
QuerySet methods apply SQL-like conditions using Pythonic syntax with field lookups.
# Filter products using conditions
from .models import Product
products = Product.objects.filter(price__gt=100)
products_in_category = Product.objects.filter(category='Electronics')
# Retrieve a single unique object
from .models import Product
product = Product.objects.get(id=1)
product_by_name = Product.objects.get(name='Laptop')
# 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)
# Chain multiple QuerySet methods
from .models import Product
products = Product.objects.filter(category='Electronics', price__gt=100)\
.exclude(stock=0)\
.order_by('price')
Each chained method refines the query. Django executes the final SQL query only when data is accessed.
| ID | Product | Category | Price ($) | Stock |
|---|
filter() over get() unless uniqueness is guaranteedget()order_by()