Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django QuerySet Query API

Django's QuerySet Query API allows you to create complex database queries using a simple and consistent syntax. In this tutorial, we will cover the basics of the QuerySet Query API.

  1. Basic Queries
  2. Chaining Filters
  3. Field Lookups
  4. Q Objects
  5. Aggregations and Annotations

1. Basic Queries

To query the database, you need a model. Let's assume we have a model called Book in our Django app:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    is_available = models.BooleanField(default=True)

You can perform basic queries using the following methods:

  • all(): Returns a QuerySet containing all objects in the database.

    books = Book.objects.all()
    
  • filter(**kwargs): Returns a QuerySet containing objects that match the specified filters.

    available_books = Book.objects.filter(is_available=True)
    
  • exclude(**kwargs): Returns a QuerySet containing objects that do not match the specified filters.

    unavailable_books = Book.objects.exclude(is_available=True)
    
  • get(**kwargs): Returns a single object that matches the specified filters. Raises Book.DoesNotExist if no objects are found and Book.MultipleObjectsReturned if multiple objects are found.

    book = Book.objects.get(id=1)
    

2. Chaining Filters

You can chain multiple filter() or exclude() methods to refine your query:

from datetime import date

available_books_before_today = Book.objects.filter(is_available=True).filter(published_date__lt=date.today())

3. Field Lookups

You can use field lookups to perform queries based on field values. Field lookups are specified using the double underscore (__) syntax:

# Find books with titles that contain the word "Django"
books = Book.objects.filter(title__icontains="Django")

# Find books published before a specific date
books = Book.objects.filter(published_date__lt=date(2020, 1, 1))

4. Q Objects

You can use Q objects to create complex queries with OR conditions:

from django.db.models import Q

# Find books that are either written by "Author1" or have "Django" in their title
books = Book.objects.filter(Q(author="Author1") | Q(title__icontains="Django"))

5. Aggregations and Annotations

You can use aggregation functions like Count, Sum, Avg, Min, and Max to perform calculations on your QuerySet:

from django.db.models import Count, Avg

# Count the number of books
book_count = Book.objects.count()

# Count the number of available books
available_book_count = Book.objects.filter(is_available=True).count()

# Get the average length of book titles
average_title_length = Book.objects.aggregate(Avg('title__length'))

In this tutorial, we've covered the basics of Django's QuerySet Query API, including basic queries, chaining filters, field lookups, Q objects, and aggregations. These tools allow you to create complex database queries with a consistent and readable syntax.

  1. Django QuerySet Filter Examples:

    • Description: Use the filter() method to narrow down query results based on specified conditions.
    • Code:
      # Retrieve all entries with 'category' equal to 'Tech'
      queryset = MyModel.objects.filter(category='Tech')
      
  2. Django QuerySet Exclude Method:

    • Description: Use the exclude() method to exclude entries that meet certain conditions.
    • Code:
      # Exclude entries with 'status' equal to 'Inactive'
      queryset = MyModel.objects.exclude(status='Inactive')
      
  3. Django QuerySet Annotate Method:

    • Description: Use the annotate() method to add aggregated values to each object in the QuerySet.
    • Code:
      from django.db.models import Count
      
      # Annotate the queryset with the count of related items
      queryset = MyModel.objects.annotate(item_count=Count('related_items'))
      
  4. Django QuerySet Values Method:

    • Description: Use the values() method to retrieve specific fields as dictionaries.
    • Code:
      # Retrieve only 'name' and 'price' fields as dictionaries
      queryset = MyModel.objects.values('name', 'price')
      
  5. Django QuerySet Order By Examples:

    • Description: Use the order_by() method to sort the queryset based on one or more fields.
    • Code:
      # Order queryset by 'date_published' in descending order
      queryset = MyModel.objects.order_by('-date_published')
      
  6. Django QuerySet Aggregation Examples:

    • Description: Utilize the aggregate() method to perform aggregations on the queryset.
    • Code:
      from django.db.models import Sum
      
      # Get the total sum of 'price' for all items
      total_price = MyModel.objects.aggregate(total_price=Sum('price'))
      
  7. Django QuerySet Complex Lookups:

    • Description: Combine multiple conditions using complex lookups for intricate queries.
    • Code:
      # Retrieve entries with 'category' equals 'Tech' and 'status' not equals 'Inactive'
      queryset = MyModel.objects.filter(category='Tech', status__ne='Inactive')
      
  8. Django QuerySet Chaining Queries:

    • Description: Chain multiple query methods to build complex queries.
    • Code:
      # Chaining filter and exclude to get a specific subset of entries
      queryset = MyModel.objects.filter(category='Tech').exclude(status='Inactive')
      
  9. Django QuerySet Raw SQL Queries:

    • Description: Use the raw() method to execute raw SQL queries with the queryset.
    • Code:
      # Execute a raw SQL query
      queryset = MyModel.objects.raw('SELECT * FROM myapp_mymodel WHERE category = %s', ['Tech'])
      
  10. Django QuerySet Date Filtering:

    • Description: Filter queryset based on date-related conditions.
    • Code:
      from datetime import date
      
      # Retrieve entries published after a specific date
      queryset = MyModel.objects.filter(date_published__gt=date(2023, 1, 1))
      
  11. Django QuerySet Distinct Values:

    • Description: Use the distinct() method to get distinct values from the queryset.
    • Code:
      # Get distinct values for the 'category' field
      queryset = MyModel.objects.values('category').distinct()
      
  12. Django QuerySet Count Method:

    • Description: Use the count() method to get the number of objects in the queryset.
    • Code:
      # Get the count of items with 'status' equal to 'Active'
      count_active_items = MyModel.objects.filter(status='Active').count()
      
  13. Django QuerySet Slicing and Limiting Results:

    • Description: Use slicing to limit the number of results returned by the queryset.
    • Code:
      # Retrieve the first 5 entries
      queryset = MyModel.objects.all()[:5]
      
  14. Django QuerySet Update Method:

    • Description: Use the update() method to perform bulk updates on queryset items.
    • Code:
      # Update the 'status' of all items to 'Inactive'
      MyModel.objects.all().update(status='Inactive')