Django Database Queries


Django Data Lookup

Once you’ve created models and added entries, you’ll often need to fetch or modify information stored in your database. Django’s built-in tool for this is called the ORM (Object-Relational Mapper). It allows you to interact with your tables using Python code instead of raw SQL.


What Is the ORM?

ORM is a feature that turns database tables into Python classes and rows into objects. This lets you read and change data in a simple and safe way.


How to Retrieve Entries

To get all rows from a model like Member, use:

from members.models import Member  

All_members = Member.objects.all() 

This returns a collection of all stored members as Python-friendly records.


Getting Specific Records

You can filter by a field:

Member.objects.filter(firstname='Parmi')

This fetches every person whose firstname matches "Parmi".

To grab a single exact match:

Member.objects.get(id=1)

If there’s no match, or more than one result, this will raise an error.


Sorting Results

Order data using:

Member.objects.order_by('lastname')

Prefix a field with a minus (-) to sort in reverse:

Member.objects.order_by('-firstname')

Limit or Slice Results

Only want the first three entries?

Member.objects.all()[:3]

This works just like Python list slicing.


Conditions and Logic

You can use more advanced lookups:

Member.objects.filter(firstname__contains='ar')

This gets all records where the name includes the letters "ar".

Other lookups include:

  • startswith
  • endswith
  • iexact (case-insensitive match)
  • gt, lt, gte, lte for comparing numbers or dates

Counting Records

To check how many entries exist:

Member.objects.count()

Deleting Entries

You can remove a specific record:

person = Member.objects.get(id=2) 
Person.delete() 

Or delete multiple at once:

Member.objects.filter(lastname='Shah').delete()

Updating Entries

To modify a record:

person = Member.objects.get(id=3) 
person.firstname = 'Raj' 
Person.save() 

You must call save() to apply the changes.


Creating New Entries

Add a new person like this:

new_member = Member(firstname='Aisha', lastname='Khan') 
New_member.save()

This adds a row to the database.


Quick Summary

  • Django ORM makes interacting with databases simple
  • Use .all(), .filter(), .get() to retrieve data
  • Apply .delete() and .save() to remove or update
  • Sort, limit, and count records using friendly syntax

Prefer Learning by Watching?

Watch these YouTube tutorials to understand HTML Tutorial visually:

What You'll Learn:
  • 📌 How Model Queries Work in Django
  • 📌 #15 Django tutorials | ORM | Object Relational Mapper | Theory
Previous Next