Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Query Database Operation

In this tutorial, we will cover basic query operations to interact with the database using Django's Object-Relational Mapping (ORM).

Prerequisites:

  • Basic knowledge of Python
  • Familiarity with Django framework
  • A Django project set up and running
  • A Django app with at least one model

Assuming we have an app named 'myapp' with the following models.py:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    publication_date = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
  • Creating records:

To create a new record in the database, you can use the create method or instantiate the model and call the save method.

Example:

from myapp.models import Author, Book
from datetime import date

# Using the create method
author = Author.objects.create(name="John Doe")

# Instantiating the model and calling save
book = Book(title="Sample Book", author=author, publication_date=date.today(), price=9.99)
book.save()
  • Retrieving records:

To fetch records from the database, you can use various methods provided by the ORM, such as all, get, filter, and exclude.

Example:

# Fetch all records
all_books = Book.objects.all()

# Fetch a single record based on a unique field
author = Author.objects.get(name="John Doe")

# Fetch records based on a condition
books_by_john_doe = Book.objects.filter(author=author)

# Fetch records excluding a condition
books_not_by_john_doe = Book.objects.exclude(author=author)
  • Updating records:

To update a record, fetch it from the database, modify the fields, and call the save method.

Example:

# Fetch a single record
book = Book.objects.get(title="Sample Book")

# Modify the field and save
book.price = 12.99
book.save()

You can also use the update method to update multiple records in a single query:

books_by_john_doe.update(price=14.99)
  • Deleting records:

To delete a record, fetch it from the database and call the delete method.

Example:

# Fetch a single record
book = Book.objects.get(title="Sample Book")

# Delete the record
book.delete()
  • Chaining methods:

Django's ORM allows you to chain methods to create more complex queries.

Example:

# Fetch books published in 2022 and priced below $20
from datetime import date
books = Book.objects.filter(publication_date__year=2022, price__lt=20)

In this tutorial, we covered basic database operations using Django's ORM. By using the ORM, you can interact with your database in a Pythonic way without writing raw SQL queries, making your code more maintainable and easier to understand.

  1. Django database queries examples:

    • Description: Django provides a powerful ORM for interacting with databases. Basic queries involve creating, retrieving, updating, and deleting records.
    • Code Examples:
      # Creating a new record
      new_instance = MyModel(field1='value1', field2='value2')
      new_instance.save()
      
      # Retrieving records
      all_records = MyModel.objects.all()
      
      # Updating a record
      record_to_update = MyModel.objects.get(id=1)
      record_to_update.field1 = 'new_value'
      record_to_update.save()
      
      # Deleting a record
      record_to_delete = MyModel.objects.get(id=1)
      record_to_delete.delete()
      
  2. Django filter() function examples:

    • Description: The filter() method is used to narrow down query results based on specified conditions.
    • Code Examples:
      # Basic filter
      queryset = MyModel.objects.filter(field1='value1')
      
      # Multiple conditions
      queryset = MyModel.objects.filter(field1='value1', field2__gt=10)
      
      # Case-insensitive filter
      queryset = MyModel.objects.filter(field1__iexact='value1')
      
  3. Django model queries examples:

    • Description: Model queries involve interacting with the database using the Django model.
    • Code Examples:
      # Get a single record
      instance = MyModel.objects.get(id=1)
      
      # Get the first record
      first_instance = MyModel.objects.first()
      
      # Get the count of records
      record_count = MyModel.objects.count()
      
  4. Django annotate() and aggregate() examples:

    • Description: annotate() is used to add extra fields to each object in the queryset, and aggregate() is used to perform aggregate functions on the entire queryset.
    • Code Examples:
      from django.db.models import Count, Sum
      
      # Annotate example
      queryset = MyModel.objects.annotate(comment_count=Count('comments'))
      
      # Aggregate example
      total_likes = MyModel.objects.aggregate(total_likes=Sum('likes'))
      
  5. Django querying related models:

    • Description: Querying related models involves accessing data from related models using relationships like ForeignKey or ManyToManyField.
    • Code Examples:
      # Accessing related objects
      author = Author.objects.get(name='John Doe')
      books_by_author = author.book_set.all()
      
      # Reverse relationships
      book = Book.objects.get(title='My Book')
      author_of_book = book.author
      
  6. Django complex queries examples:

    • Description: Complex queries may involve chaining multiple filters, using Q objects, or combining different query techniques.
    • Code Examples:
      from django.db.models import Q
      
      # Complex query using Q objects
      queryset = MyModel.objects.filter(Q(field1='value1') | Q(field2='value2'))
      
  7. Django select_related() and prefetch_related() examples:

    • Description: These methods optimize database queries by selecting related objects in advance to minimize database hits.
    • Code Examples:
      # select_related example
      queryset = MyModel.objects.select_related('related_model')
      
      # prefetch_related example
      queryset = MyModel.objects.prefetch_related('related_models')
      
  8. Django bulk create and update operations:

    • Description: Bulk operations allow creating or updating multiple records in a single database query for improved efficiency.
    • Code Examples:
      # Bulk create
      MyModel.objects.bulk_create([MyModel(field1='value1'), MyModel(field1='value2')])
      
      # Bulk update
      MyModel.objects.filter(field1='old_value').update(field1='new_value')
      
  9. Advanced Django database querying techniques:

    • Description: Advanced techniques may include using F expressions, conditional expressions, or raw SQL queries for specific scenarios.
    • Code Examples:
      from django.db.models import F, Case, When
      
      # F expressions
      queryset = MyModel.objects.filter(counter__gt=F('threshold'))
      
      # Conditional expressions
      queryset = MyModel.objects.annotate(status=Case(When(condition=True, then='active', default='inactive')))