Django ORM
- Comprehensive guide to Django ORM including QuerySets, data filtering, and performing CRUD operations.
What is Django ORM?
Django ORM (Object Relational Mapping) allows us to interact with the database using Python code instead of SQL queries.
ORM converts:
Python code ↔ SQL queries ↔ Database
Why Use Django ORM?
No SQL knowledge required
Database-independent
Secure (prevents SQL injection)
Clean and readable code
CRUD Operations in Django ORM
CRUD stands for:
Create
Read
Update
Delete
We will use this model for examples:
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
age = models.IntegerField()
is_active = models.BooleanField(default=True)
CREATE (Insert Data)
Using save()
Insert Record Using save()
Creates an object and saves it to the database.
student = Student(
name="Hinal",
email="hinal@gmail.com",
age=22
)
student.save()
Using objects.create()
Insert Record Using create()
Student.objects.create(
name="Amit",
email="amit@gmail.com",
age=24
)
READ (Fetch Data)
Fetch All Records
Fetch All Students
students = Student.objects.all()
Fetch Single Student
student = Student.objects.get(id=1)
Fetch First & Last Record
Student.objects.first()
Student.objects.last()
Update Student Record
student = Student.objects.get(id=1)
student.age = 23
student.save()
Update Multiple Records
Student.objects.filter(is_active=True).update(age=25)
Delete Single Record
student = Student.objects.get(id=1)
student.delete()
Delete Multiple Records
Student.objects.filter(is_active=False).delete()
QuerySets in Django ORM
What is a QuerySet?
A QuerySet is a collection of database records.
students = Student.objects.all()
QuerySets are lazy → database is hit only when needed.
Filtering Data (WHERE Clause)
filter()
Filter Students by Age
students = Student.objects.filter(age=22)
exclude()
Exclude Records
students = Student.objects.exclude(age=22)
Multiple Conditions
Student.objects.filter(age=22, is_active=True)
Field Lookups (Advanced Filters)
greater than / less than
Student.objects.filter(age__gt=20)
Student.objects.filter(age__lt=25)
contains / icontains
Student.objects.filter(name__contains="hi")
Student.objects.filter(name__icontains="hi")
in lookup
Student.objects.filter(age__in=[20, 22, 24])
startswith / endswith
Student.objects.filter(name__startswith="H")
Student.objects.filter(email__endswith="gmail.com")
Ordering & Limiting Data
order_by()
Order Students
Student.objects.order_by('age') # Ascending
Student.objects.order_by('-age') # Descending
Limit Records
Student.objects.all()[:5]
- Counting & Existence
count()
Student.objects.count()
exists()
Student.objects.filter(email="test@gmail.com").exists()