Lesson 29 of 60 – Django ORM
48%

Django ORM

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.

Note: Django ORM connects your Python models with the database and provides methods for creating, reading, updating, and deleting records.

1. What is Django ORM?

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

2. Why Use Django ORM?

The ORM simplifies database operations and allows developers to work with models using Python.

  • Less SQL for common operations
  • Python-based database operations
  • Works with Django models
  • Supports multiple database backends
  • Provides filtering and ordering
  • Supports relationships between models

3. ORM and Models

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.

4. The objects Manager

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.

5. QuerySet

A QuerySet represents a collection of database records obtained through the Django ORM.

students = Student.objects.all()

The variable students contains a QuerySet.

6. Retrieve All Records

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)

7. Create a Record

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.

8. Create Using objects.create()

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.

9. Retrieve One Record with get()

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.

10. Filtering Records

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.

11. Excluding 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.

12. Field Lookups

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

13. contains Lookup

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.

14. startswith Lookup

The startswith lookup finds values beginning with specified text.

students = Student.objects.filter(
    name__startswith="A"
)

This can be useful for simple prefix searches.

15. Case-Insensitive Lookups

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.

16. Ordering QuerySets

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'
)

17. Counting Records

Use count() to count records in a QuerySet.

total_students = Student.objects.count()

The result is an integer representing the number of matching records.

18. First and Last 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()

19. Updating a Record

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.

20. Updating Multiple Records

The update() method can update multiple matching records.

Student.objects.filter(
    age=20
).update(
    age=21
)

This performs the update directly through the QuerySet.

21. Deleting a Record

A model object can be deleted using the delete() method.

student = Student.objects.get(
    id=1
)

student.delete()

The corresponding database record is removed.

22. Deleting Multiple Records

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.

23. values()

The values() method returns QuerySet results as dictionaries.

students = Student.objects.values(
    'name',
    'age'
)

A result may look conceptually like:

{
    'name': 'Rahul',
    'age': 20
}

24. values_list()

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.

25. distinct()

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.

26. Chaining ORM Methods

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.

27. Lazy QuerySets

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.

28. ORM in a View

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}
    )

29. Complete ORM CRUD Example

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.

30. Summary of 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.
  • QuerySets can be chained together.

📌 Key Points

  • Django ORM stands for Object-Relational Mapper.
  • The ORM allows Python code to interact with database records.
  • Django ORM works with models defined in 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.
  • QuerySets support filtering, ordering, chaining, and many other operations.

🧠 Quick Quiz

Question: Which Django ORM method is commonly used to retrieve all records from a model?