The all() and filter() methods help you get data from your database easily. They let you find all records or only the ones you want.
0
0
all() and filter() methods in Django
Introduction
When you want to get every item from a database table.
When you want to find items that match certain rules, like all users with age over 18.
When you want to show a list of filtered results on a webpage.
When you want to check if some data exists by filtering with conditions.
Syntax
Django
ModelName.objects.all()
ModelName.objects.filter(field_name=value)all() returns all records from the database table.
filter() returns only records that match the conditions you give.
Examples
Gets all books from the Book table.
Django
Book.objects.all()
Gets users who are 18 years old or older.
Django
User.objects.filter(age__gte=18)
Gets products in the 'toys' category that are in stock.
Django
Product.objects.filter(category='toys', in_stock=True)
Sample Program
This example shows how to get all users and then only users who are 18 or older. It prints their names to the console.
Django
from django.db import models class User(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() # Imagine we have these users in the database: # User(name='Alice', age=25) # User(name='Bob', age=17) # User(name='Charlie', age=30) # Get all users all_users = User.objects.all() # Get users aged 18 or older adult_users = User.objects.filter(age__gte=18) # Print names of all users print('All users:') for user in all_users: print(user.name) # Print names of adult users print('\nAdult users:') for user in adult_users: print(user.name)
OutputSuccess
Important Notes
Use filter() to narrow down results with conditions.
Both methods return QuerySets, which act like lists but get data only when needed.
You can chain filters for more complex queries, like .filter(age__gte=18).filter(name__startswith='A').
Summary
all() gets every record from a table.
filter() gets records that match your conditions.
Use these methods to easily find and work with data in Django.