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.

  1. from datetime import date
  2. uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
  3. uncle_bob.save() # bob is now stored in the database
  4. # 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:

  1. grandma = Person.create(name='Grandma', birthday=date(1935, 3, 1))
  2. 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:

  1. grandma.name = 'Grandma L.'
  2. grandma.save() # Update grandma's name in the database.
  3. # 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:

  1. bob_kitty = Pet.create(owner=uncle_bob, name='Kitty', animal_type='cat')
  2. herb_fido = Pet.create(owner=herb, name='Fido', animal_type='dog')
  3. herb_mittens = Pet.create(owner=herb, name='Mittens', animal_type='cat')
  4. 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:

  1. herb_mittens.delete_instance() # he had a great life
  2. # 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:

  1. herb_fido.owner = uncle_bob
  2. herb_fido.save()