What is Django's Object-relational mapping (ORM)?

Photo by Faisal on Unsplash

What is Django's Object-relational mapping (ORM)?

Play this article

Django's Object-relational mapping (ORM) feature is a way to interact with databases using Python code, rather than writing raw SQL queries. It allows developers to work with databases using Python classes and objects, rather than tables and rows. To use the ORM, you first need to define your database models as Python classes, with each class representing a table in the database. The fields of the class correspond to the columns in the table, and you can specify the type of each field (e.g. CharField for a string, IntegerField for an integer, etc.). For example, to define a simple model for a "Person" with a name and age, you would do something like

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

Once you have defined your models, you can use the ORM to create, read, update, and delete (CRUD) records in the database. For example, to create a new Person instance and save it to the database:

p = Person(name="John Smith", age=30)
p.save()

To retrieve all Person records from the database:

people = Person.objects.all()

To filter records based on certain criteria:

people = Person.objects.filter(age__gt=30)

To update a certain record:

p = Person.objects.get(name="John Smith")
p.age = 31
p.save()

To delete a certain record:

p = Person.objects.get(name="John Smith")
p.delete()

When using the ORM, Django will automatically handle the creation of the database tables, as well as any necessary migrations when the models change. This can save a lot of time and effort compared to writing raw SQL queries, and also makes it easier to switch between different database backends (e.g. from SQLite to PostgreSQL). It's worth mentioning that the ORM feature also allows the management of relationships between tables, such as one-to-one, many-to-one and many-to-many. For example, you can define a one-to-many relationship between two models by using a ForeignKey field on the "one" side of the relationship:

class Book(models.Model):
    title = models.CharField(max_length=100)

class Chapter(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

This will create a relationship between the books and chapters tables, where each book can have multiple chapters, but each chapter belongs to only one book.

ORM is a very powerful feature of Django that allows developers to work with databases in a more intuitive and pythonic way. It can save a lot of time and effort compared to writing raw SQL queries and makes it easier to switch between different database backends. Subscribe and look out for future posts.