Labs ICT
โญ Pro Login

QuerySets

The Django way to query your database.

What Are QuerySets?

QuerySets are how you retrieve data from the database in Django. They're lazy โ€” meaning they don't hit the database until you actually evaluate them. This lets you build complex queries efficiently.

Think of a QuerySet as a chain of database operations. You can filter, sort, and transform your data without ever writing raw SQL.

Basic Retrieval Methods

Django provides several methods to fetch data. Each serves a specific purpose.


all_posts = Post.objects.all()
published = Post.objects.filter(published=True)
not_published = Post.objects.exclude(published=True)
single_post = Post.objects.get(pk=1)
    

all() returns everything. filter() returns matching records. exclude() returns non-matching records. get() returns exactly one object โ€” it raises an error if there are zero or multiple matches.

Refining Your Queries

You can chain methods to build complex queries step by step. Django evaluates them only when needed.


results = Post.objects.filter(published=True).order_by('-created_at')[:10]
post_data = Post.objects.values('title', 'created_at')
unique_authors = Post.objects.values('author').distinct()
total = Post.objects.count()
exists = Post.objects.filter(title='Hello').exists()
first = Post.objects.first()
last = Post.objects.last()
    

The values() method returns dictionaries instead of model instances โ€” useful for APIs. distinct() removes duplicates. count() and exists() are efficient because they use SQL COUNT.

Try it Yourself โ†’

Q Objects and F Objects

When you need complex conditions, Django gives you Q objects for OR queries and F objects for field-to-field comparisons.


from django.db.models import Q, F

results = Post.objects.filter(
    Q(title__icontains='django') | Q(content__icontains='python')
)

Post.objects.filter(views__gt=F('likes'))
    

Q objects let you combine conditions with OR, AND, and NOT. F objects let you compare fields against each other without fetching the data first. These are powerful tools you'll reach for often.

๐Ÿงช Quick Quiz

What does the QuerySet method filter() do?