Nitin Raturi
Nitin Raturi's Software Engineering Blog

Follow

Nitin Raturi's Software Engineering Blog

Follow
Django ORM Tutorial

Photo by Toa Heftiba on Unsplash

Django ORM Tutorial

Nitin Raturi's photo
Nitin Raturi
ยทSep 14, 2018ยท

5 min read

Django ORM (Object-Relational Mapping) is a powerful and flexible tool for interacting with databases in Django web applications. It provides an intuitive and efficient way of interacting with relational databases without having to write SQL code directly.

Models

The heart of the Django ORM is the Model class, which represents a database table. To define a model, we create a Python class that inherits from the django.db.models.Model class. We then define the fields that correspond to the columns of the table as attributes of the class.

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    published_date = models.DateField()

In this example, we define a Book model with three fields: title, author, and published_date. The title and author fields are of type CharField, which represents a string, and have a maximum length of 200 characters. The published_date field is of type DateField, which represents a date.

Querying Data

Once we have defined our models, we can use the Django ORM to interact with the database. To query data from the database, we use the objects attribute of the model class. This attribute is an instance of the django.db.models.Manager class, which provides a set of methods for querying the database.

books = Book.objects.all()

In this example, we use the all() method of the Book.objects manager to retrieve all the books in the database. The result is a queryset, which is a lazily-evaluated list-like object that represents a collection of database objects.

We can filter the queryset using the filter() method, which takes one or more keyword arguments that represent the conditions that the objects must meet.

recent_books = Book.objects.filter(published_date__gte='2022-01-01')

In this example, we use the filter() method to retrieve all the books that were published in or after January 1, 2022. The published_dategte argument represents the condition that the published_date field must be greater than or equal to the specified date.

We can also chain multiple filters together using the Q object.

from django.db.models import Q

popular_books = Book.objects.filter(Q(author__startswith='J.K.') | Q(title__startswith='Harry Potter'))

In this example, we use the Q object to retrieve all the books that were either written by an author whose name starts with "J.K." or whose title starts with "Harry Potter".

We can also order the queryset using the order_by() method, which takes one or more arguments that represent the fields to order by.

recent_books = Book.objects.filter(published_date__gte='2022-01-01').order_by('-published_date')

In this example, we use the order_by() method to retrieve all the books that were published in or after January 1, 2022, and order them in descending order of publication date.

Creating and Updating Data

To create a new object in the database, we create a new instance of the model class and call its save() method.

new_book = Book(title='The Alchemist', author='Paulo Coelho', published_date='1988-04-25')
new_book.save()

In this example, we create a new Book object with the title "The Alchemist", the author "Paulo Coelho", and the publication date April 25, we then call its save() method to save it to the database.

To update an existing object, we retrieve it from the database using the objects manager, modify its attributes, and call its save() method.

book = Book.objects.get(title='The Alchemist')
book.published_date = '2014-08-14'
book.save()

In this example, we retrieve the Book object with the title "The Alchemist" from the database, change its publication date to August 14, 2014, and save it back to the database.

Deleting Data

To delete an object from the database, we call its delete() method.

book = Book.objects.get(title='The Alchemist')
book.delete()

In this example, we retrieve the Book object with the title "The Alchemist" from the database and delete it.

Relationships

Django ORM also supports defining relationships between models, such as one-to-many and many-to-many relationships.

One-to-Many Relationships

A one-to-many relationship is a relationship in which one object of one model is related to multiple objects of another model.

For example, we can define a Publisher model and a Book model, where each publisher can publish multiple books.

class Publisher(models.Model):
    name = models.CharField(max_length=200)

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    published_date = models.DateField()
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

In this example, we define a Publisher model with a name field, and a Book model with a publisher field that is a foreign key to the Publisher model.

To retrieve all the books published by a specific publisher, we can use the reverse relation provided by the publisher foreign key.

publisher = Publisher.objects.get(name='HarperCollins')
books = publisher.book_set.all()

In this example, we retrieve the Publisher object with the name "HarperCollins" from the database, and use its book_set attribute to retrieve all the books published by that publisher.

Many-to-Many Relationships

A many-to-many relationship is a relationship in which multiple objects of one model are related to multiple objects of another model.

For example, we can define a Tag model and a Book model, where each book can have multiple tags and each tag can be associated with multiple books.

class Tag(models.Model):
    name = models.CharField(max_length=200)

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    published_date = models.DateField()
    tags = models.ManyToManyField(Tag)

In this example, we define a Tag model with a name field, and a Book model with a tags field that is a many-to-many relationship to the Tag model.

To retrieve all the books that are associated with a specific tag, we can use the reverse relation provided by the tags many-to-many relationship.

tag = Tag.objects.get(name='Fiction')
books = tag.book_set.all()

In this example, we retrieve the Tag object with the name "Fiction" from the database, and use its book_set attribute to retrieve all the books that are associated with that tag.

Conclusion

In conclusion, the Django ORM provides a powerful and flexible way of interacting with relational databases in Django web applications. By defining Python classes that represent database tables and fields

Did you find this article valuable?

Support Nitin Raturi by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this