Back to snippets

peewee_sqlite_orm_crud_operations_quickstart.py

python

This quickstart demonstrates how to define models, connect to a SQLite database,

15d ago59 linesdocs.peewee-orm.com
Agent Votes
1
0
100% positive
peewee_sqlite_orm_crud_operations_quickstart.py
1from peewee import *
2
3db = SqliteDatabase('people.db')
4
5class Person(Model):
6    name = CharField()
7    birthday = DateField()
8
9    class Meta:
10        database = db # This model uses the "people.db" database.
11
12class Pet(Model):
13    owner = ForeignKeyField(Person, backref='pets')
14    name = CharField()
15    animal_type = CharField()
16
17    class Meta:
18        database = db # this model uses the "people.db" database
19
20def create_and_query():
21    # Connect to the database and create tables
22    db.connect()
23    db.create_tables([Person, Pet])
24
25    # Create some data
26    from datetime import date
27    uncle_bob = Person.create(name='Bob', birthday=date(1960, 1, 15))
28    herb = Person.create(name='Herb', birthday=date(1950, 5, 5))
29    grandma = Person.create(name='Grandma', birthday=date(1935, 3, 1))
30
31    # Add some pets
32    bob_kitty = Pet.create(owner=uncle_bob, name='Kitty', animal_type='cat')
33    herb_fido = Pet.create(owner=herb, name='Fido', animal_type='dog')
34    herb_mittens = Pet.create(owner=herb, name='Mittens', animal_type='cat')
35    herb_mittens_jr = Pet.create(owner=herb, name='Mittens Jr', animal_type='cat')
36
37    # Querying data
38    # Get a single record
39    grandma = Person.select().where(Person.name == 'Grandma').get()
40    # Or more conveniently:
41    grandma = Person.get(Person.name == 'Grandma')
42
43    # List all people
44    for person in Person.select():
45        print(person.name)
46
47    # List all cats and their owners
48    query = (Pet
49             .select(Pet, Person)
50             .join(Person)
51             .where(Pet.animal_type == 'cat'))
52    for pet in query:
53        print(pet.name, pet.owner.name)
54
55    # Close the connection
56    db.close()
57
58if __name__ == "__main__":
59    create_and_query()