Django ORM stands for Object-Relational Mapper. It allows you to interact with a database using Python objects and methods instead of writing SQL queries for common database operations.
Django ORM is a layer between your Django application and the database. It allows Python code to work with database records through model classes.
Python Code
↓
Django ORM
↓
Database
The ORM simplifies database operations and allows developers to work with models using Python.
Django ORM works directly with the models defined in models.py.
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
Django uses this model to provide database operations through the ORM.
Django models normally have an objects manager that provides ORM
methods for querying the database.
Student.objects.all()
Here, objects is the manager and all() retrieves
records.
A QuerySet represents a collection of database records obtained through the Django ORM.
students = Student.objects.all()
The variable students contains a QuerySet.
Use all() to retrieve all records from a model.
students = Student.objects.all()
You can iterate over the QuerySet:
for student in students:
print(student.name)
A model object can be created using the model class.
student = Student(
name="Rahul",
age=20
)
student.save()
The save() method writes the object to the database.
Django also provides the create() method for creating and saving a
record in one operation.
student = Student.objects.create(
name="Amit",
age=21
)
The returned object represents the newly created database record.
The get() method is used when you expect exactly one matching
object.
student = Student.objects.get(
id=1
)
If no object matches, Django raises DoesNotExist. If multiple
objects match, Django raises MultipleObjectsReturned.
Use filter() to retrieve records matching specified conditions.
students = Student.objects.filter(
age=20
)
The result is a QuerySet and can contain zero, one, or many records.
The exclude() method returns records that do not match the
specified condition.
students = Student.objects.exclude(
age=20
)
This retrieves students whose age is not 20.
Django ORM provides field lookups for more advanced filtering.
Student.objects.filter(
age__gte=18
)
Here, __gte means greater than or equal to.
Other examples include:
age__gt
age__lt
age__lte
name__startswith
name__contains
The contains lookup can find values containing specific text.
students = Student.objects.filter(
name__contains="Rah"
)
The exact matching behavior can depend on the lookup and database backend.
The startswith lookup finds values beginning with specified text.
students = Student.objects.filter(
name__startswith="A"
)
This can be useful for simple prefix searches.
Django provides icontains and other case-insensitive lookups.
students = Student.objects.filter(
name__icontains="rahul"
)
This can match names such as Rahul without requiring the same
letter case.
Use order_by() to control the ordering of query results.
students = Student.objects.order_by(
'name'
)
Use a minus sign for descending order:
students = Student.objects.order_by(
'-age'
)
Use count() to count records in a QuerySet.
total_students = Student.objects.count()
The result is an integer representing the number of matching records.
The first() and last() methods can return the first
and last objects from an ordered QuerySet.
first_student = Student.objects.order_by(
'name'
).first()
last_student = Student.objects.order_by(
'name'
).last()
Retrieve an object, change its fields, and call save().
student = Student.objects.get(id=1)
student.age = 22
student.save()
This updates the database record.
The update() method can update multiple matching records.
Student.objects.filter(
age=20
).update(
age=21
)
This performs the update directly through the QuerySet.
A model object can be deleted using the delete() method.
student = Student.objects.get(
id=1
)
student.delete()
The corresponding database record is removed.
A QuerySet can also be deleted.
Student.objects.filter(
age=18
).delete()
This can remove all matching records, so always check the filter carefully before performing destructive operations.
The values() method returns QuerySet results as dictionaries.
students = Student.objects.values(
'name',
'age'
)
A result may look conceptually like:
{
'name': 'Rahul',
'age': 20
}
The values_list() method returns selected field values as tuples.
students = Student.objects.values_list(
'name',
'age'
)
It is useful when you need selected field values rather than complete model objects.
The distinct() method can remove duplicate rows from a QuerySet
when the database query produces duplicates.
students = Student.objects.values(
'city'
).distinct()
The exact SQL behavior can depend on the query and database backend.
Many QuerySet methods can be chained together.
students = Student.objects.filter(
age__gte=18
).order_by(
'name'
)
This filters the records first and then orders the result.
Django QuerySets are generally lazy. Creating a QuerySet does not always mean that the database query is immediately executed.
students = Student.objects.filter(
age__gte=18
)
The query is evaluated when Django needs the actual results, such as when iterating over the QuerySet.
Django ORM can be used inside a view to retrieve records and send them to a template.
from django.shortcuts import render
from .models import Student
def students(request):
data = Student.objects.all()
return render(
request,
'students/list.html',
{'students': data}
)
Create:
student = Student.objects.create(
name="Rahul",
age=20
)
Read:
students = Student.objects.all()
student = Student.objects.get(
id=1
)
Update:
Student.objects.filter(
id=1
).update(
age=21
)
Delete:
Student.objects.filter(
id=1
).delete()
These four operations form the basic CRUD workflow used with the Django ORM.
Django ORM provides Python-based tools for interacting with database records through Django models.
objects.all() retrieves all records.objects.create() creates and saves a record.get() retrieves one expected record.filter() retrieves matching records.exclude() excludes matching records.order_by() sorts QuerySet results.count() counts records.update() updates records.delete() deletes records.values() returns dictionary-style results.values_list() returns selected values.models.py.objects.all() retrieves all records.filter() retrieves records matching conditions.get() is used when one specific object is expected.create() can create and save a record in one operation.update() changes matching records.delete() removes records.Question: Which Django ORM method is commonly used to retrieve all records from a model?