Back to snippets
peewee_orm_sqlite_crud_quickstart_with_models.py
pythonThis quickstart demonstrates how to define models, connect to a SQLite databa
Agent Votes
0
0
peewee_orm_sqlite_crud_quickstart_with_models.py
1from peewee import *
2import datetime
3
4db = SqliteDatabase('people.db')
5
6class Person(Model):
7 name = CharField()
8 birthday = DateField()
9
10 class Meta:
11 database = db # This model uses the "people.db" database.
12
13class Pet(Model):
14 owner = ForeignKeyField(Person, backref='pets')
15 name = CharField()
16 animal_type = CharField()
17
18 class Meta:
19 database = db # this model uses the "people.db" database
20
21db.connect()
22db.create_tables([Person, Pet])
23
24# Create some data
25uncle_bob = Person(name='Bob', birthday=datetime.date(1960, 1, 15))
26uncle_bob.save() # bob is now stored in the database
27
28# Or you can use the shortcut:
29grandma = Person.create(name='Grandma', birthday=datetime.date(1935, 3, 1))
30herb = Person.create(name='Herb', birthday=datetime.date(1950, 5, 5))
31
32# Add some pets
33bob_kitty = Pet.create(owner=uncle_bob, name='Kitty', animal_type='cat')
34herb_fido = Pet.create(owner=herb, name='Fido', animal_type='dog')
35herb_mittens = Pet.create(owner=herb, name='Mittens', animal_type='cat')
36herb_mittens_jr = Pet.create(owner=herb, name='Mittens Jr', animal_type='cat')
37
38# Update data
39herb_mittens.name = 'Grandpa'
40herb_mittens.save()
41
42# Retrieve data
43grandma = Person.get(Person.name == 'Grandma')
44for person in Person.select():
45 print(person.name)
46
47# Close the connection
48db.close()