Unlocking the Power of Django ORM: A Step-by-Step Guide with Hands-On Examples

Learn how to effectively use the Django ORM with a step-by-step guide and real-world examples. Optimize your queries, use built-in and custom managers, and more.

image description

Unlocking the Power of Django ORM: A Step-by-Step Guide with Hands-On Examples

Learn how to effectively use the Django ORM with a step-by-step guide and real-world examples. Optimize your queries, use built-in and custom managers, and more. Django is a web framework for Python that includes an Object-Relational Mapper (ORM) to interact with databases. The ORM allows developers to interact with databases using Python code, rather than writing raw SQL queries.

Django's ORM is a powerful tool for interacting with databases using Python. In this tutorial, we'll go over the basics of using the Django ORM to create, read, update, and delete data in a database. We'll also cover advanced techniques such as how to optimize your queries and how to use the built-in manager and custom manager.

  1. Defining Models: In Django, a model is a Python class that represents a database table. Each attribute of the class represents a column in the table. You can define your models in a models.py file. For example, the following code defines a Book model with three fields: title, author, and pub_date.
from django.db import models

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

In this example, we're using the CharField and DateField field types, but Django also provides many other field types such as IntegerField, BooleanField, TextField, etc.

  1. Creating the Database Table: Once you've defined your models, you need to create the corresponding database tables. You can do this by running the following command:
python manage.py makemigrations
python manage.py migrate

This will create the necessary tables in your database.

Using the Model to Create, Read, Update and Delete Data: Now that we have our models defined and the corresponding database tables created, we can use the models to create, read, update, and delete data in the database.

Creating a new Object:

book = Book(title="The Great Gatsby", author="F. Scott Fitzgerald", pub_date="1925-04-10")
book.save()

Retrieving data from database:

all_books = Book.objects.all()
gatsby = Book.objects.get(title="The Great Gatsby")

Updating an object:

gatsby = Book.objects.get(title="The Great Gatsby")
gatsby.author = "Francis Scott Fitzgerald"
gatsby.save()

Deleting an object:

gatsby = Book.objects.get(title="The Great Gatsby")
gatsby.delete()
  1. ForeignKey and OneToOneField :Django provides two types of fields for representing relationships between models: ForeignKey and OneToOneField.
  2. ForeignKey: This field is used to create a one-to-many relationship between two models. For example, the following code defines a Book model that has a foreign key to an Author model.
class Author(models.Model):
    name = models.CharField(max_length=100)
    bio = models.TextField()

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    pub_date = models.DateField()

create a one-to-one relationship between two models. Here's an example of how to use the OneToOneField:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()
    location = models.CharField(max_length=100)

In this example, we've created a Profile model that has a OneToOneField to the built-in Django User model.

  1. Querysets:A queryset is a set of objects returned by a database query. You can use querysets to retrieve and manipulate data from the database. You can chain multiple filters together to create complex queries. for example:
from django.utils import timezone
recent_books = Book.objects.filter(pub_date__year__gte=2000, pub_date__lte=timezone.now())

 

  1. Custom Manager: A manager is the interface through which database query operations are provided to Django models. By default, Django adds a manager called objects to every Django model class. However, you can also create custom managers by subclassing the models.Manager class and adding it to your model. For example:
class BookManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(pub_date__year__gte=2000)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    pub_date = models.DateField()
    objects = models.Manager()
    new_books = BookManager()

 

  1. Queries:
    • You can also use advanced query techniques, such as select_related() and prefetch_related(), to optimize your queries and avoid the N+1 problem.
    • select_related() and prefetch_related() can also be used to prefetch related data, which can result in significant performance improvements.
    • Q objects to make more complex queries.
    • F() objects allows to perform operations in the DB with fields of a model
    • Using the Model to Create, Read, Update and Delete Data: You can use the models to create, read, update, and delete data in the database. The basic methods to interact with the models are:
    • save(): used to create or update an object in the database.
    • create(): used to create a new object and save it to the database in one step.
    • all(): used to retrieve all objects from the database.
    • get(): used to retrieve a single object that matches the specified lookups.
    • filter(): used to retrieve a set of objects that match the specified lookups.
    • exclude(): used to retrieve a set of objects that do not match the specified lookups.
    • delete(): used to delete an object from the database.

This blog post is aimed to give you a solid understanding of how to use the Django ORM to interact with a database. I recommend to check the official Django documentation for more details: https://docs.djangoproject.com/en/3.2/topics/db/models/ Also, you can find more real-world examples and explore different options that the ORM provides to understand how to use it in a given scenario.

DigitalOcean Referral Badge

DigitalOcean Sign Up : If you don't have a DigitalOcean account yet, you can sign up using the link below and receive $200 credit for 60 days to get started: Start your free trial with a $200 credit for 60 days link below: Get $200 free credit on DigitalOcean ( Note: This is a referral link, meaning both you and I will get credit.)


Latest From PyDjangoBoy

👩💻🔍 Explore Python, Django, Django-Rest, PySpark, web 🌐 & big data 📊. Enjoy coding! 🚀📚