Storing data
Let’s begin by populating the database with some people. We will use thesave()
and create()
methods to add and updatepeople’s records.
- from datetime import date
- uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
- uncle_bob.save() # bob is now stored in the database
- # Returns: 1
Note
When you call save()
, the number of rows modified isreturned.
You can also add a person by calling the create()
method, whichreturns a model instance:
- grandma = Person.create(name='Grandma', birthday=date(1935, 3, 1))
- herb = Person.create(name='Herb', birthday=date(1950, 5, 5))
To update a row, modify the model instance and call save()
topersist the changes. Here we will change Grandma’s name and then save thechanges in the database:
- grandma.name = 'Grandma L.'
- grandma.save() # Update grandma's name in the database.
- # Returns: 1
Now we have stored 3 people in the database. Let’s give them some pets. Grandmadoesn’t like animals in the house, so she won’t have any, but Herb is an animallover:
- bob_kitty = Pet.create(owner=uncle_bob, name='Kitty', animal_type='cat')
- herb_fido = Pet.create(owner=herb, name='Fido', animal_type='dog')
- herb_mittens = Pet.create(owner=herb, name='Mittens', animal_type='cat')
- herb_mittens_jr = Pet.create(owner=herb, name='Mittens Jr', animal_type='cat')
After a long full life, Mittens sickens and dies. We need to remove him fromthe database:
- herb_mittens.delete_instance() # he had a great life
- # Returns: 1
Note
The return value of delete_instance()
is the number of rowsremoved from the database.
Uncle Bob decides that too many animals have been dying at Herb’s house, so headopts Fido:
- herb_fido.owner = uncle_bob
- herb_fido.save()