Defining Your First Table
A database holds data in tables — think of a table like a spreadsheet. It has columns (the fields) and rows (the individual records).
In PookieDB, you define a table by writing a Python class.
A class is a table
Here is a Patient table with two columns — name and age:
import pookiedb
pookiedb.connect("sqlite:///patients.sqlite3")
class Patient(pookiedb.Model):
name = pookiedb.CharField(max_length=100)
age = pookiedb.IntegerField()
class Meta:
db_table = "patients"
Breaking it down:
class Patient(pookiedb.Model)— your class inherits frompookiedb.Model. That is what makes it a database table instead of a plain Python class.name = pookiedb.CharField(max_length=100)— a text column, up to 100 charactersage = pookiedb.IntegerField()— a whole number columnclass Meta: db_table = "patients"— tells PookieDB what to name the table in the database. Keep it lowercase, no spaces.
Field types you will use
| Field | Use it for |
|---|---|
CharField(max_length=N) |
Short text — names, titles, labels |
IntegerField() |
Whole numbers — age, count, quantity |
TextField() |
Longer text — descriptions, notes, messages |
That is all you need for now.
Creating the table
Defining the class does not create the table yet. You need one more line:
Patient.create_table()
This creates the patients table in the database file. It is safe to call every time your program runs — if the table already exists, PookieDB leaves it alone and does not delete your data.
The complete database.py
import pookiedb
pookiedb.connect("sqlite:///patients.sqlite3")
class Patient(pookiedb.Model):
name = pookiedb.CharField(max_length=100)
age = pookiedb.IntegerField()
class Meta:
db_table = "patients"
Patient.create_table()
Run this file once. The patients.sqlite3 file appears in your folder, and inside it the patients table is ready and waiting.
PookieDB adds an id column automatically
Every table gets an id column for free — a unique number that identifies each row. You do not define it yourself. PookieDB handles it.
Challenge
Add the Patient class and create_table() call to your database.py from the previous page. Run it. No errors means the table was created successfully. Try defining a second model — a Doctor with name and specialty (both CharField) — and call create_table() on that too.
← What is PookieDB? Next: Adding, Reading, Updating, Deleting →