Skip to content

PookieDB Exercises

These exercises practice everything from the last three pages. You will build two files — database.py for the database logic, and main.py for the code that uses it. Keep them separate throughout.


The rule before you start

your-exercise-folder/
├── database.py    ← connection, model, create_table()
└── main.py        ← imports from database, does the actual work

DB logic stays in database.py. Everything else goes in main.py. This is the habit to build.


Exercise 1 — Set Up the Database

In database.py:

  • Import PookieDB and connect to a SQLite file called library.sqlite3
  • Define a Book model with three fields:
  • titleCharField(max_length=200)
  • authorCharField(max_length=100)
  • yearIntegerField()
  • Set db_table = "books" in the Meta class
  • Call Book.create_table()

Run database.py. The library.sqlite3 file should appear in your folder.


Exercise 2 — Add Books

In main.py:

from database import Book

Use Book.objects.create() to add five books. Use real titles, authors, and years — anything you actually know.

Run main.py. No errors means all five were saved.


Exercise 3 — Read All Books

Still in main.py, after adding the books, loop through Book.objects.all() and print each book's title and author on one line.

Your output should look something like:

Things Fall Apart — Chinua Achebe
1984 — George Orwell
...

Exercise 4 — Filter by Year

Add a filter() call that finds only books published after the year 2000. Print the titles of the results.

If none of your five books are from after 2000, add one that is, then filter.


Exercise 5 — Update a Title

Pick one of your books. Use filter(id=...) and bulk_update() to change its title to something else.

After the update, use get(id=...) to fetch that same book and print its title. Confirm the change took effect.


Exercise 6 — Delete a Book

Delete one book using filter(id=...).delete().

Then call Book.objects.all() and print the remaining books. The deleted one should not appear.

Stop main.py and run it again. The deleted book should still be gone — because it was removed from the database file, not just from memory.


What if you want to start fresh?

Delete the library.sqlite3 file from your folder and run database.py again. A clean empty database is created. This is the quickest way to reset during practice.


← Adding, Reading, Updating, Deleting    Next: Connecting PookieDB to Flask →