Recommended preparation: set up a Django project and read the Django tutorial overview before trying the code.
Use the Django ORM to retrieve rows from a MySQL-backed model, sort and filter results, and pass them to an HTML template. These examples use the Student model shared with the insert and admin tutorials.
students/views.py — first 20 students ordered by ID
from django.shortcuts import render
from .models import Student
def student_list(request):
students = Student.objects.order_by("id")[:20]
return render(request, "students/student_list.html", {"students": students})
Start with objects.all(), then apply name and mark filters and display the results in a template. Limit or paginate rows on large datasets.
students/models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
cl = models.CharField(max_length=20, db_column="class")
mark = models.PositiveSmallIntegerField()
gender = models.CharField(max_length=20)
def __str__(self):
return self.name
students/urls.py
from django.urls import path
from . import views
app_name = "students"
urlpatterns = [path("", views.student_list, name="list")]
students/templates/students/student_list.html
<h1>Students</h1>
<table>
<thead><tr><th>ID</th><th>Name</th><th>Class</th><th>Mark</th><th>Gender</th></tr></thead>
<tbody>
{% for student in students %}
<tr>
<td>{{ student.id }}</td><td>{{ student.name }}</td>
<td>{{ student.cl }}</td><td>{{ student.mark }}</td>
<td>{{ student.gender }}</td>
</tr>
{% empty %}
<tr><td colspan="5">No records found.</td></tr>
{% endfor %}
</tbody>
</table>
Django shell — all(), ascending and descending order
from students.models import Student
all_students = Student.objects.all()
first_ten = Student.objects.order_by("id")[:10]
latest_ten = Student.objects.order_by("-id")[:10]
Sorting matters when slicing QuerySets. Example records such as John Deo, Max Ruin and Arnold are available from the linked student dataset.
Return records at positions 6–10 of the ordered QuerySet
students = Student.objects.order_by("id")[5:10]
Python-style slicing is zero-based and the end index is exclusive. Avoid passing unchecked negative or huge user-controlled indexes into database slices.
filter() returns QuerySets, even if only one row matches
by_name = Student.objects.filter(name="Arnold")
by_id = Student.objects.filter(pk=30)
startswith, gte, gt, lte and lt lookups
names_starting_a = Student.objects.filter(name__startswith="A")
mark_at_least_90 = Student.objects.filter(mark__gte=90)
mark_above_90 = Student.objects.filter(mark__gt=90)
mark_at_most_55 = Student.objects.filter(mark__lte=55)
mark_below_55 = Student.objects.filter(mark__lt=55)
| Lookup | Meaning |
|---|---|
name__startswith="A" | Names that begin with the letter A |
mark__gte=90 | Mark greater than or equal to 90 |
mark__gt=90 | Mark strictly greater than 90 |
mark__lte=55 | Mark less than or equal to 55 |
mark__lt=55 | Mark strictly less than 55 |
Return a 404 response when the ID does not exist
from django.shortcuts import get_object_or_404, render
from .models import Student
def student_detail(request, pk):
student = get_object_or_404(Student, pk=pk)
return render(request, "students/student_detail.html", {"student": student})
Student.objects.get(pk=14) raises Student.DoesNotExist when missing, unlike filter(). The view helper above is appropriate for browser-facing detail pages. Continue to the linked list and detail tutorial.
Use 20 rows per page instead of loading an entire table
from django.core.paginator import Paginator
from django.shortcuts import render
from .models import Student
def student_list(request):
paginator = Paginator(Student.objects.order_by("id"), 20)
page = paginator.get_page(request.GET.get("page"))
return render(request, "students/list_page.html", {"page": page})
Pagination controls in templates/students/list_page.html
{% for student in page %}
<p>{{ student.name }} — {{ student.mark }}</p>
{% empty %}
<p>No students found.</p>
{% endfor %}
{% if page.has_previous %}<a href="?page={{ page.previous_page_number }}">Previous</a>{% endif %}
Page {{ page.number }} of {{ page.paginator.num_pages }}
{% if page.has_next %}<a href="?page={{ page.next_page_number }}">Next</a>{% endif %}
For the underlying Python containers see lists and dictionaries. The SQL ORDER BY tutorial explains the database-level concept. Django QuerySets generate SQL and provide an ORM layer.
cl instead of an invented class Python attribute.The 35-row sample dataset includes Arnold (ID 3, mark 55), Alex John (ID 6, mark 55), and Asruid (ID 8, mark 85). The following filters demonstrate typical lookups. Exact results assume the sample file was imported with those IDs.
Exact-match name filter
Student.objects.filter(name="Arnold").values("id", "name", "mark")
Expected output
<QuerySet [{'id': 3, 'name': 'Arnold', 'mark': 55}]>
Exact primary-key filter
Student.objects.filter(pk=30).values("id", "name", "mark")
Expected output
<QuerySet [{'id': 30, 'name': 'Reppy Red', 'mark': 79}]>
Filter student names starting with A
Student.objects.filter(name__startswith="A").order_by("id").values_list("id", "name")
Expected output
<QuerySet [(3, 'Arnold'), (6, 'Alex John'), (8, 'Asruid')]>
Marks greater than or equal to 90
Student.objects.filter(mark__gte=90).order_by("id").values_list("name", "mark")
Expected output
<QuerySet [('Recky', 94), ('Binn Rott', 90), ('Kenn Rein', 96)]>
Marks strictly greater than 90
Student.objects.filter(mark__gt=90).order_by("id").values_list("name", "mark")
Expected output
<QuerySet [('Recky', 94), ('Kenn Rein', 96)]>
Marks less than or equal to 55
Student.objects.filter(mark__lte=55).order_by("id").values_list("name", "mark")
Expected output
<QuerySet [('Arnold', 55), ('Alex John', 55), ('Big John', 55), ('Tumyu', 54), ('Tinny', 18), ('Reggid', 55), ('Tess Played', 55)]>
Marks strictly less than 55
Student.objects.filter(mark__lt=55).order_by("id").values_list("name", "mark")
Expected output
<QuerySet [('Tumyu', 54), ('Tinny', 18)]>
Rows at offsets 5–9
Student.objects.order_by("id")[5:10].values_list("id", "name")
Expected output
<QuerySet [(6, 'Alex John'), (7, 'My John Rob'), (8, 'Asruid'), (9, 'Tes Qry'), (10, 'Big John')]>
Last five IDs from the sample dataset
Student.objects.order_by("-id")[:5].values_list("id", "name")
Expected output
<QuerySet [(35, 'Rows Noump'), (34, 'Gain Toe'), (33, 'Kenn Rein'), (32, 'Binn Rott'), (31, 'Marry Toeey')]>
For production sites, show only the data each user is authorized to see. These results are instructional examples based on the provided sample file, not live database output.
No. It returns an empty QuerySet that your template can handle with {% empty %}.
Use order_by("-id")[:10] to return the ten highest IDs first.
No. Pass the QuerySet from the view to a template and iterate over its items.
Previous: Insert multiple records
Next: List and detail pages
Browse the complete Django tutorial series.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
28-12-2020 | |
| how to display only one record....can you tell me | |
26-04-2021 | |
| how to display only one record....can you tell me pls ThankYou, | |
17-02-2022 | |
| I am not getting the class student on the html page. | |