Inserting and Updating Data

You’ve already seen this done: to insert a row into your database, first create an instance of your model using keyword arguments, like so:

>>> p = Publisher(name=’Apress’,…         address=’2855 Telegraph Ave.’,…         city=’Berkeley’,…         state_province=’CA’,…         country=’U.S.A.’,…         website=’http://www.apress.com/’)

This act of instantiating a model class does not touch the database.

To save the record into the database (i.e., to perform the SQL INSERT statement), call the object’s save() method:

>>> p.save()

In SQL, this can roughly be translated into the following:

INSERT INTO book_publisher   (name, address, city, state_province, country, website)VALUES   (‘Apress’, ‘2855 Telegraph Ave.’, ‘Berkeley’, ‘CA’,     ‘U.S.A.’, ‘http://www.apress.com/’);

Because the Publisher model uses an autoincrementing primary key id, the initial call to save() does one more thing: it calculates the primary key value for the record and sets it to the id attribute on the instance:

>>> p.id52   # this will differ based on your own data

Subsequent calls to save() will save the record in place, without creating a new record (i.e., performing an SQL UPDATE statement instead of an INSERT):

>>> p.name = ‘Apress Publishing’>>> p.save()

The preceding save() statement will result in roughly the following SQL:

UPDATE book_publisher SET   name = ‘Apress Publishing’,   address = ‘2855 Telegraph Ave.’,   city = ‘Berkeley’,   state_province = ‘CA’,   country = ‘U.S.A.’,   website = ‘http://www.apress.com’WHERE id = 52;

Back to Tutorial

Get industry recognized certification – Contact us

Menu