Querying Data Using Django ORM

Tutorial 3 of 5

1. Introduction

In this tutorial, we will explore how to query data using Django ORM (Object-relational Mapping). Django ORM simplifies the interaction with your database by translating Python code into SQL queries. By the end of this tutorial, you will be able to create simple and complex queries to retrieve data from your database.

What will you learn?
- Querying data from a single Django model
- Querying data from multiple Django models (joining)
- Filtering, ordering, and limiting queries

Prerequisites
- Basic knowledge of Python and Django
- A functional Django project with a connected database

2. Step-by-Step Guide

Understanding Django ORM

Django ORM is a powerful tool that lets you interact with your database like Python objects. It abstracts the underlying SQL queries for you.

Fetching Data

To fetch data, Django ORM provides several methods that you can use on your model.

Filtering Data

The filter() method is used to filter the query set based on the given conditions.

Ordering Data

You can order the query set by using the order_by() method.

Limiting Data

The slicing syntax can be used to limit the query set.

3. Code Examples

Fetching Data

Assuming we have a Book model in our Django application.

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

To fetch all books:

books = Book.objects.all()

Filtering Data

To get all books written by an author named 'John Doe':

books = Book.objects.filter(author='John Doe')

Ordering Data

To get all books ordered by published_date:

books = Book.objects.all().order_by('published_date')

Limiting Data

To get the first 5 books:

books = Book.objects.all()[:5]

4. Summary

We have covered how to fetch, filter, order, and limit data using Django ORM. Now you can try querying your data in different ways. For further learning, you can explore complex queries, aggregation, and annotation in Django ORM.

5. Practice Exercises

  1. Fetch all books published in the year 2020.
  2. Fetch the top 10 books ordered by the number of pages.
  3. Fetch all books written by 'John Doe' and order them by published_date.

Solutions

1.

from datetime import date
books = Book.objects.filter(published_date__year=2020)

2.

books = Book.objects.all().order_by('-number_of_pages')[:10]

3.

books = Book.objects.filter(author='John Doe').order_by('published_date')

Remember, practice is key to mastering Django ORM queries. Happy coding!