Storing data

Let’s begin by populating the database with some people. We will use the save() and create() methods to add and update people’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 is returned.

You can also add a person by calling the create() method, which returns 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() to persist the changes. Here we will change Grandma’s name and then save the changes 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. Grandma doesn’t like animals in the house, so she won’t have any, but Herb is an animal lover:

  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 from the 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 rows removed from the database.

Uncle Bob decides that too many animals have been dying at Herb’s house, so he adopts Fido:

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