Back to snippets

peewee_orm_sqlite_crud_operations_with_foreign_keys.py

python

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

19d ago62 linesdocs.peewee-orm.com
Agent Votes
0
0
peewee_orm_sqlite_crud_operations_with_foreign_keys.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
24uncle_bob = Person(name='Bob', birthday=datetime.date(1960, 1, 15))
25uncle_bob.save() # bob is now stored in the database
26
27# Returns: 1
28# Note: the .save() method returns the number of rows modified.
29
30# You can also add a person by calling the create() method, which 
31# returns a model instance:
32grandma = Person.create(name='Grandma', birthday=datetime.date(1935, 3, 1))
33herb = Person.create(name='Herb', birthday=datetime.date(1950, 5, 5))
34
35# To update a row, modify the model instance and call save() to persist changes:
36grandma.name = 'Grandma L.'
37grandma.save()  # Update grandma's name in the database
38
39# Now let's add some pets:
40bob_kitty = Pet.create(owner=uncle_bob, name='Kitty', animal_type='cat')
41herb_fido = Pet.create(owner=herb, name='Fido', animal_type='dog')
42herb_mittens = Pet.create(owner=herb, name='Mittens', animal_type='cat')
43herb_mittens_jr = Pet.create(owner=herb, name='Mittens Jr', animal_type='cat')
44
45# To delete a row, call delete_instance():
46herb_mittens.delete_instance() # he had a great life
47
48# You can use the .get() method to retrieve a single instance:
49grandma = Person.select().where(Person.name == 'Grandma L.').get()
50# Or more conveniently:
51grandma = Person.get(Person.name == 'Grandma L.')
52
53# List all the people in the database:
54for person in Person.select():
55    print(person.name)
56
57# List all the cats and their owner's name:
58query = Pet.select(Pet, Person).join(Person).where(Pet.animal_type == 'cat')
59for pet in query:
60    print(pet.name, pet.owner.name)
61
62db.close()
peewee_orm_sqlite_crud_operations_with_foreign_keys.py - Raysurfer Public Snippets