Reading Data (get, filter, all, values)
Reading data is the most common operation. Django provides get() for single records, filter() for multiple records with conditions, all() for everything, and values()/values_list() for optimized dictionary/tuple output.
20 min•By Priygop Team•Updated 2026
Read Methods
- all() — All records as QuerySet
- get(pk=1) — Single record (raises DoesNotExist or MultipleObjectsReturned)
- filter() — Records matching conditions
- exclude() — Records NOT matching conditions
- first() / last() — First/last record or None
- values('field1', 'field2') — Returns dictionaries
- values_list('field', flat=True) — Returns flat list
- exists() — Returns True/False without loading data
- count() — Count without loading all records
Read Examples
Read Examples
# Reading data
# from blog.models import Post
# All records
# posts = Post.objects.all()
# Single record — raises exception if not found
# post = Post.objects.get(pk=1)
# post = Post.objects.get(slug='my-post')
# Safe single record
# post = Post.objects.filter(pk=1).first() # Returns None if not found
# Filtering with lookups
# Post.objects.filter(published=True)
# Post.objects.filter(title__icontains='django')
# Post.objects.filter(created_at__year=2026)
# Post.objects.filter(views_count__gte=100)
# Post.objects.filter(category__name='Python') # FK lookup
# Excluding
# Post.objects.exclude(author=admin_user)
# Optimized output
# Post.objects.values('id', 'title')
# # [{'id': 1, 'title': 'Hello'}, {'id': 2, 'title': 'World'}]
# Post.objects.values_list('title', flat=True)
# # ['Hello', 'World', ...]
# Efficient checks
# has_posts = Post.objects.filter(published=True).exists()
# post_count = Post.objects.count()
# Slicing (LIMIT/OFFSET)
# latest_5 = Post.objects.order_by('-created_at')[:5]
# page_2 = Post.objects.all()[10:20]Tip
Tip
Use ModelForm to auto-generate forms from models. It creates fields, validates data, and saves to database with one .save() call.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Manually creating forms when ModelForm would auto-generate them. ModelForm saves massive amounts of boilerplate.
Practice Task
Note
(1) Create a ModelForm for a Post model. (2) Customize the fields list. (3) Save data in the view with form.save().
Quick Quiz
Key Takeaways
- Reading data is the most common operation.
- all() — All records as QuerySet
- get(pk=1) — Single record (raises DoesNotExist or MultipleObjectsReturned)
- filter() — Records matching conditions