Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django ORM Module

Django's Object-Relational Mapping (ORM) is a powerful tool that allows you to interact with your database like you would with Python objects. In this tutorial, we will cover the basics of Django ORM, including:

  1. Creating a model
  2. Querying the database
  3. Creating, updating, and deleting records

1. Creating a model

A Django model is a Python class that inherits from django.db.models.Model and defines the structure of a database table.

Let's create a simple model for a Book:

# models.py
from django.db import models

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

    def __str__(self):
        return self.title

In this example, we define a Book model with three fields: title, author, and publication_date. We also define a __str__() method that returns a string representation of the book.

Run python manage.py makemigrations and python manage.py migrate to create the database table for the Book model.

2. Querying the database

Django ORM provides a high-level API to query the database. To query the database, you interact with the model's manager, which is an instance of django.db.models.Manager. By default, Django adds a manager named objects to every model.

Here are some examples of common queries:

  • Retrieve all books:

    books = Book.objects.all()
    
  • Retrieve books filtered by a certain condition:

    books = Book.objects.filter(author='John Doe')
    
  • Retrieve a single book by its primary key:

    book = Book.objects.get(pk=1)
    
  • Retrieve a book that meets certain conditions or return a default value:

    book = Book.objects.filter(author='John Doe').first()  # Returns the first book found or None.
    
  • Retrieve books ordered by a certain field:

    books = Book.objects.order_by('publication_date')
    

3. Creating, updating, and deleting records

Django ORM also provides an API to create, update, and delete records in the database.

  • Creating a new record:

    book = Book(title='The Catcher in the Rye', author='J.D. Salinger', publication_date='1951-07-16')
    book.save()
    

    Alternatively, you can use the create() method:

    book = Book.objects.create(title='The Catcher in the Rye', author='J.D. Salinger', publication_date='1951-07-16')
    
  • Updating a record:

    book = Book.objects.get(pk=1)
    book.author = 'Jane Doe'
    book.save()
    
  • Deleting a record:

    book = Book.objects.get(pk=1)
    book.delete()
    

That's it! With this tutorial, you've learned the basics of Django ORM, including creating models, querying the database, and creating, updating, and deleting records. Django ORM abstracts away the complexities of working with databases, allowing you to focus on writing Python code rather than SQL queries.

  1. Using Django ORM for database interaction:

    Django's Object-Relational Mapping (ORM) simplifies database interactions by allowing developers to work with Python objects instead of raw SQL queries. It abstracts the database layer, making it more accessible.

    # Example model using Django ORM
    from django.db import models
    
    class MyModel(models.Model):
        name = models.CharField(max_length=255)
        age = models.IntegerField()