Session Overview

  • QuerySets Introduction
  • Fetching Data from Database
  • Passing Data to Template
  • Displaying Records Using for Loop
  • Empty Data Handling
  • Filtering and Ordering Data

QuerySets Introduction

A QuerySet is a collection of records retrieved from a database table.

Django uses QuerySets to read data from database tables.

Example
Category.objects.all()

The above statement retrieves all records from the Category table.

Think Like This:
Category Table
       ↓
QuerySet
       ↓
Python Object
       ↓
Template
SQL Equivalent
SELECT * FROM Category;

Django converts:

Category.objects.all()
into an SQL query internally.

Fetching Data from Database

We can retrieve records from the Category table using QuerySets.

File Location
demo/views.py
Import Category Model
from .models import Category
Fetch Records
from django.shortcuts import render

from .models import Category

def categories(request):

    categories = Category.objects.all()

    return render(
        request,
        'categories.html'
    )

Passing Data to Template

After retrieving records from the database, we must send them to the Template.

Update View
from django.shortcuts import render

from .models import Category

def categories(request):

    categories = Category.objects.all()

    return render(
        request,
        'categories.html',
        {
            'categories': categories
        }
    )
Understanding the Code
Code Purpose
Category.objects.all() Fetch All Records
categories Stores QuerySet
'categories':categories Send Data To Template
Remember
Database
    ↓
QuerySet
    ↓
View
    ↓
Template
The View acts as a bridge between the Database and the Template.

Displaying Records Using for Loop

Django Templates use the for tag to display multiple records.

File Location
demo/templates/categories.html
Display Records
{% extends 'base.html' %}

{% block content %}

<h2>Categories</h2>

<ul>

    {% for item in categories %}

        <li>{{ item.Name }}</li>

    {% endfor %}

</ul>

{% endblock %}
Output
Technology

Travel

Food

Empty Data Handling

Sometimes a database table may not contain any records.

Instead of displaying a blank page, we should show a meaningful message.

Example
{% extends 'base.html' %}

{% block content %}

<h2>Categories</h2>

{% if categories %}

    <ul>

        {% for item in categories %}

            <li>{{ item.Name }}</li>

        {% endfor %}

    </ul>

{% else %}

    <p>No Categories Available</p>

{% endif %}

{% endblock %}
Result: If records exist, they will be displayed. If no records exist, "No Categories Available" will be shown.

Filtering Data

Django allows us to retrieve specific records using filters.

Instead of fetching all records, we can fetch only the records that match a condition.

Example
Category.objects.filter(Name='Technology')
SQL Equivalent
SELECT *
FROM Category
WHERE Name='Technology';
Result: Only categories having the name Technology will be returned.
Fetch Single Record
Category.objects.get(Id=1)
SQL Equivalent
SELECT *
FROM Category
WHERE Id = 1;
Common QuerySet Methods
Method Purpose
all() Retrieve All Records
filter() Retrieve Matching Records
get() Retrieve Single Record

Ordering Data

Django allows records to be sorted in ascending or descending order.

Ascending Order
Category.objects.all().order_by('Name')
Descending Order
Category.objects.all().order_by('-Name')
SQL Equivalent
SELECT *
FROM Category
ORDER BY Name ASC;
SELECT *
FROM Category
ORDER BY Name DESC;
Note: Prefixing a field with '-' sorts the records in descending order.

Quick Revision

QuerySets
  • Retrieve Data
  • Database Access
  • Model Objects
all()
  • Fetch All Records
  • Returns QuerySet
  • Most Common Method
Passing Data
  • View To Template
  • Dictionary
  • Dynamic Content
Template Loop
  • for Tag
  • Display Records
  • Repeat Content
Conditional Display
  • if
  • else
  • Empty Data Handling
Filtering
  • filter()
  • get()
  • order_by()
Most Important QuerySet Methods
Category.objects.all()

Category.objects.filter(Name='Technology')

Category.objects.get(Id=1)

Category.objects.order_by('Name')
Complete Flow
Database Table
       ↓
QuerySet
       ↓
View
       ↓
Template
       ↓
Web Page

Assignment

Complete the following tasks:
  1. Add at least 5 Category records using the Django Admin Panel.
  2. Create a new View named:
    categories
  3. Retrieve all Category records using:
    Category.objects.all()
  4. Pass the QuerySet to a Template.
  5. Display all Categories using a Django for loop.
  6. Show the message:
    No Categories Available
    when the table contains no records.
  7. Display Categories using Bootstrap List Group.
  8. Sort Categories alphabetically using:
    Category.objects.order_by('Name')
Company Logo
Full Stack Development Training - Python Django