A QuerySet is a collection of records retrieved from a database table.
Django uses QuerySets to read data from database tables.
Category.objects.all()
The above statement retrieves all records from the Category table.
Category Table
↓
QuerySet
↓
Python Object
↓
Template
SELECT * FROM Category;
Django converts:
Category.objects.all()
into an SQL query internally.
We can retrieve records from the Category table using QuerySets.
demo/views.py
from .models import Category
from django.shortcuts import render
from .models import Category
def categories(request):
categories = Category.objects.all()
return render(
request,
'categories.html'
)
After retrieving records from the database, we must send them to the Template.
from django.shortcuts import render
from .models import Category
def categories(request):
categories = Category.objects.all()
return render(
request,
'categories.html',
{
'categories': categories
}
)
| Code | Purpose |
|---|---|
| Category.objects.all() | Fetch All Records |
| categories | Stores QuerySet |
| 'categories':categories | Send Data To Template |
Database
↓
QuerySet
↓
View
↓
Template
The View acts as a bridge between the Database and the Template.
Django Templates use the for tag to display multiple records.
demo/templates/categories.html
{% extends 'base.html' %}
{% block content %}
<h2>Categories</h2>
<ul>
{% for item in categories %}
<li>{{ item.Name }}</li>
{% endfor %}
</ul>
{% endblock %}
Technology
Travel
Food
Sometimes a database table may not contain any records.
Instead of displaying a blank page, we should show a meaningful message.
{% 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 %}
Django allows us to retrieve specific records using filters.
Instead of fetching all records, we can fetch only the records that match a condition.
Category.objects.filter(Name='Technology')
SELECT *
FROM Category
WHERE Name='Technology';
Category.objects.get(Id=1)
SELECT *
FROM Category
WHERE Id = 1;
| Method | Purpose |
|---|---|
| all() | Retrieve All Records |
| filter() | Retrieve Matching Records |
| get() | Retrieve Single Record |
Django allows records to be sorted in ascending or descending order.
Category.objects.all().order_by('Name')
Category.objects.all().order_by('-Name')
SELECT *
FROM Category
ORDER BY Name ASC;
SELECT *
FROM Category
ORDER BY Name DESC;
Category.objects.all()
Category.objects.filter(Name='Technology')
Category.objects.get(Id=1)
Category.objects.order_by('Name')
Database Table
↓
QuerySet
↓
View
↓
Template
↓
Web Page
categories
Category.objects.all()
No Categories Available
when the table contains no records.
Category.objects.order_by('Name')