Adding, Reading, Updating, Deleting
You have a table. Now let's put data in it, read it back, change it, and remove it. These four operations — often called CRUD (Create, Read, Update, Delete) — are everything you do with a database.
All the examples below assume database.py already has the connection, the Patient model, and create_table(). You run each snippet in a separate main.py that imports Patient from it:
# main.py
from database import Patient
Add — create()
from database import Patient
Patient.objects.create(name="Alice", age=24)
Patient.objects.create(name="Bob", age=31)
Patient.objects.create(name="Carol", age=19)
Each call adds one row to the patients table. Run this and the data is saved permanently — stop the program, start it again, and the records are still there.
Read all — all()
from database import Patient
patients = Patient.objects.all()
for patient in patients:
print(patient.name, patient.age)
all() returns every row in the table. You loop through them just like a Python list. Each item is a Patient object — access its fields with dot notation: patient.name, patient.age.
Read one — get()
from database import Patient
patient = Patient.objects.get(id=1)
print(patient.name)
get() fetches a single row that matches the condition. Use id to find a specific record by its unique number.
Filter — filter()
from database import Patient
results = Patient.objects.filter(name="Alice")
for patient in results:
print(patient.name, patient.age)
filter() returns all rows that match. You can filter by any field.
Update — bulk_update()
from database import Patient
Patient.objects.filter(id=1).bulk_update(age=25)
Chain filter() to find the row you want, then call bulk_update() with the new values. This updates every row that the filter matched — here just the one with id=1.
Delete — delete()
from database import Patient
Patient.objects.filter(id=1).delete()
Same pattern — filter to find the row, then call delete(). That row is permanently removed from the table.
The full picture
# main.py
from database import Patient
# Add
Patient.objects.create(name="Alice", age=24)
Patient.objects.create(name="Bob", age=31)
# Read all
for p in Patient.objects.all():
print(p.id, p.name, p.age)
# Update
Patient.objects.filter(id=1).bulk_update(age=25)
# Confirm update
alice = Patient.objects.get(id=1)
print("Updated age:", alice.age)
# Delete
Patient.objects.filter(id=2).delete()
# Confirm delete
print("Remaining:", Patient.objects.all().count())
Run this. Watch the output. Every operation touches the actual .sqlite3 file — stop and restart the program and the remaining data is still there.
Challenge
In main.py, write a short script that:
- Adds three patients
- Prints all of them
- Updates the age of the first one
- Deletes the second one
- Prints all remaining patients
Stop and restart main.py. Do the remaining patients still show? They should.