ORMs
Once upon a time, if you needed to interact with a database, you had to write SQL. But now ORMs have replaced that daunting approach. ORM stands for Object Relational Mapping, it is a piece of software that converts objects in your code into rows in your database, and vise versa.
Class / Model = Table in DB
Model Attribute = Column in DB
.save() adds a new row to the table
The ORM we’ll be using is called PeeWee. As for the database we’ll be connecting to, it’ll be SQLite3.
pip install peewee
Modeling
Peewee’s convention is to import everything with *.
This is usually considered a bad practice for several reasons:
- Your local namespace suddenly gets flooded by a huge number of items.
- Things you’ve defined locally, or already imported, can be overwritten by the import.
- Peewee’s contents are no longer contained in the peewee namespace.
from peewee import *
db = SqliteDatabase('students.db')
class Student(Model):
username = CharField(max_length=255, unique=True)
points = IntegerField(default=0)
class Meta:
database = db
if __name__ == '__main__':
db.connect()
db.create_tables([Student], safe=True)
class Student(Model):
The model Student inherits from the class Model.
Models usually have singular names, because they represent a single item in the database.
class Meta
A class inside of a class. It tells the Model what database it belongs to.
if __name__ == ‘__main__’
If the app file is run directly and not imported. This condition prevents its script block from running when it’s imported/used by another program. Whereas __name__ is a special variable that refers to the current namespace. To prevent code from being executed when you import a module, put it into a function or class, or inside an if condition.
safe=True
So peewee doesn’t freak out if we run the database again and the same data was already there.