Display and Filter MySQL Records with Django

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.

On this page — Show page sectionsHide page sections

Create the Student model and route

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")]

Render rows in HTML

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>

Retrieve all records and order them

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.

Use slicing to select a range

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 by exact values

filter() returns QuerySets, even if only one row matches

by_name = Student.objects.filter(name="Arnold")
by_id = Student.objects.filter(pk=30)

Filter by prefixes and comparisons

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)
LookupMeaning
name__startswith="A"Names that begin with the letter A
mark__gte=90Mark greater than or equal to 90
mark__gt=90Mark strictly greater than 90
mark__lte=55Mark less than or equal to 55
mark__lt=55Mark strictly less than 55

Read one record safely

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.

Display results with pagination

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 %}

Further reading and common errors

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.

  • FieldError: a filter refers to a nonexistent model field; use cl instead of an invented class Python attribute.
  • No rows displayed: ensure you have migrated and inserted data, and that the template context key matches.
  • DoesNotExist: use get_object_or_404 for a record requested through a URL.
  • Slow pages: limit records, paginate and add indexes for frequently used filters.

Query recipes with verified sample rows

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.

Frequently asked questions

Does filter() raise an error when there are no matches?

No. It returns an empty QuerySet that your template can handle with {% empty %}.

How do I display the last ten records?

Use order_by("-id")[:10] to return the ten highest IDs first.

Is the data printed automatically?

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.

Additional references

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com



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.




Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer