PookieDB Refresher
Before wiring PookieDB to the frontend, let's make sure the database side is solid. You covered this earlier - this page is a quick recap with one update: we are now using UUIDs as the primary key instead of integers.
Why UUIDs
An integer id counts up: 1, 2, 3. If you know patient 3 exists, you can guess that patient 4 probably does too. That makes integer ids easy to enumerate.
A UUID looks like this: f47ac10b-58cc-4372-a567-0e02b2c3d479. It is randomly generated and practically impossible to guess. Better for any situation where records have ids that end up in URLs.
The updated model
Add id = pookiedb.UUIDField(auto=True, primary_key=True) to your model. PookieDB generates the UUID automatically every time you create a record - you never set it yourself.
import pookiedb
pookiedb.connect("sqlite:///patients.sqlite3")
class Patient(pookiedb.Model):
id = pookiedb.UUIDField(auto=True, primary_key=True)
name = pookiedb.CharField(max_length=100)
age = pookiedb.IntegerField()
class Meta:
db_table = "patients"
Patient.create_table()
Create
Patient.objects.create(name="Alice", age=24)
Patient.objects.create(name="Bob", age=31)
The id is assigned automatically. You do not pass it in.
Read all
patients = Patient.objects.all()
for patient in patients:
print(patient.id, patient.name, patient.age)
patient.id is a UUID object. To use it as a string (in a URL or JSON), convert it: str(patient.id).
Read one
patient = Patient.objects.get(id="f47ac10b-58cc-4372-a567-0e02b2c3d479")
print(patient.name)
Pass the UUID as a string. PookieDB handles the conversion.
Filter
results = Patient.objects.filter(name="Alice")
for p in results:
print(p.name, p.age)
Returns all rows where the name matches. You can filter by any field.
Update
Patient.objects.filter(id="f47ac10b-...").bulk_update(age=25)
Chain filter() to find the record, then bulk_update() with the new values. Note: it is bulk_update, not update.
Delete one record
Patient.objects.filter(id="f47ac10b-...").delete()
Permanently removes that row from the database.
Delete many records
Patient.objects.filter(name="Alice").delete()
Removes every row where name is "Alice".
Count
Patient.objects.all().count() # total rows in the table
Patient.objects.filter(name="Alice").count() # rows matching a filter
Challenge
In a fresh main.py, do all of this:
- Add two patients
- Print both of them with their UUIDs
- Update the age of the first one using its UUID
- Delete the second one
- Print the count - it should be 1
- Stop and restart the script - is the remaining patient still there?