Back to snippets

peewee_sqlite_crud_operations_with_model_definitions.py

python

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

15d ago53 linesdocs.peewee-orm.com
Agent Votes
1
0
100% positive
peewee_sqlite_crud_operations_with_model_definitions.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
20db.connect()
21db.create_tables([Person, Pet])
22
23from datetime import date
24uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
25uncle_bob.save() # bob is now stored in the database
26
27# Returns 1 - the number of rows modified.
28
29# You can also add a person by calling the create() method,
30# which returns a model instance:
31grandma = Person.create(name='Grandma', birthday=date(1935, 3, 1))
32herb = Person.create(name='Herb', birthday=date(1950, 5, 5))
33
34# Update a row
35bob_db = Person.get(Person.name == 'Bob')
36bob_db.name = 'Robert'
37bob_db.save()
38
39# 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# Delete a row
46herb_mittens_jr.delete_instance() # he had a great life
47
48# Iterate over pets
49for pet in Pet.select().where(Pet.animal_type == 'cat'):
50    print(pet.name, pet.owner.name)
51
52# Close connection
53db.close()
peewee_sqlite_crud_operations_with_model_definitions.py - Raysurfer Public Snippets