Code Self Study Forum

Peewee -- Python ORM

This looks like it could be a quick, simple way to use databases in Python where something like sqlalchemy would be overkill.

“Peewee is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use.”

https://peewee.readthedocs.io/en/latest/index.html

Here are some examples from the quickstart:

from peewee import *

db = SqliteDatabase('people.db')

# or in memory
# db = SqliteDatabase(':memory:')

class Person(Model):
    name = CharField()
    birthday = DateField()

    class Meta:
        database = db # This model uses the "people.db" database.


class Pet(Model):
    owner = ForeignKeyField(Person, backref='pets')
    name = CharField()
    animal_type = CharField()

    class Meta:
        database = db # this model uses the "people.db" database


db.connect()
db.create_tables([Person, Pet])

from datetime import date
uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
uncle_bob.save() # bob is now stored in the database

# ...

grandma = Person.get(Person.name == 'Grandma L.')

query = Pet.select().where(Pet.animal_type == 'cat')
for pet in query:
    print(pet.name, pet.owner.name)

for pet in Pet.select().join(Person).where(Person.name == 'Bob'):
    print(pet.name)
1 Like