</>
Skip to content
Django lessons (15/43)

Django — Queries

Basic Queries

# Get all objects
posts = Post.objects.all()

# Filter
posts = Post.objects.filter(published=True)

# Get single object
post = Post.objects.get(pk=1)

# Get or create
post, created = Post.objects.get_or_create(
    title='My Post',
    defaults={'content': 'Hello'}
)

QuerySet Methods

MethodDescription
all()All objects
filter()Filter by conditions
exclude()Exclude by conditions
get()Get single object
order_by()Order results
distinct()Remove duplicates
count()Count objects
exists()Check if any exist
first()Get first object
last()Get last object

Filtering

# Exact match
Post.objects.filter(title='Hello')

# Contains
Post.objects.filter(title__contains='hello')

# Case-insensitive contains
Post.objects.filter(title__icontains='hello')

# Greater than
Post.objects.filter(pk__gt=1)

# In list
Post.objects.filter(pk__in=[1, 2, 3])

# Date filters
Post.objects.filter(created_at__year=2025)

Chaining Queries

posts = Post.objects.filter(
    published=True
).filter(
    author__name='John'
).order_by('-created_at')[:10]

Complex Queries

from django.db.models import Q

posts = Post.objects.filter(
    Q(title__icontains='hello') | Q(content__icontains='hello')
)

Mini Practice

  1. Perform basic queries
  2. Use filter and exclude
  3. Chain query methods
  4. Use Q objects for complex queries

Up Next

Continue with Migrations — database schema management.

Related Topics

Frequently Asked Questions about Queries

What is Queries in Django?

Queries is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Queries?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Queries.

Why is Queries important in Django?

Queries is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.